Skip to content

Commit

Permalink
Avoid allocations with (*regexp.Regexp).MatchString (#2679)
Browse files Browse the repository at this point in the history
We should use `(*regexp.Regexp).MatchString` instead of
`(*regexp.Regexp).Match([]byte(...))` when matching string to avoid
unnecessary `[]byte` conversions and reduce allocations.

func BenchmarkMatch(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := versionRe.Match([]byte("v1")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := versionRe.MatchString("v1"); !match {
			b.Fail()
		}
	}
}

goos: linux
goarch: amd64
pkg: go-micro.dev/v4/api/handler/event
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	11430127	       127.4 ns/op	       2 B/op	       1 allocs/op
BenchmarkMatchString-16    	12220628	        97.54 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	go-micro.dev/v4/api/handler/event	3.822s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
  • Loading branch information
Juneezee authored Dec 4, 2023
1 parent 252385e commit cbd45b1
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion api/handler/event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func evRoute(namespace, myPath string) (string, string) {

// Treat /v[0-9]+ as versioning
// /v1/foo/bar => topic: v1.foo action: bar
if len(parts) >= 2 && versionRe.Match([]byte(parts[0])) {
if len(parts) >= 2 && versionRe.MatchString(parts[0]) {
topic := namespace + "." + strings.Join(parts[:2], ".")
action := eventName(parts[1:])

Expand Down

0 comments on commit cbd45b1

Please sign in to comment.