Skip to content

Conversation

@Juneezee
Copy link
Contributor

We can use (*regexp.Regexp).MatchString instead of (*regexp.Regexp).Match([]byte(...)) to avoid unnecessary []byte conversions and reduce allocations. A one-line change for free performance gain.

Benchmark:

func BenchmarkMatch(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.Match([]byte("v")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.MatchString("v"); !match {
			b.Fail()
		}
	}
}

Result:

BenchmarkMatch-16          	19712776	        65.47 ns/op	       1 B/op	       1 allocs/op
BenchmarkMatchString-16    	24261463	        51.16 ns/op	       0 B/op	       0 allocs/op

We can use `(*regexp.Regexp).MatchString` instead of
`(*regexp.Regexp).Match([]byte(...))` to avoid unnecessary `[]byte`
conversions and reduce allocations.

Example benchmark:

func BenchmarkMatch(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.Match([]byte("v")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	reg, _ := regexp.Compile("[^0-9]")

	for i := 0; i < b.N; i++ {
		if match := reg.MatchString("v"); !match {
			b.Fail()
		}
	}
}

BenchmarkMatch-16          	19712776	        65.47 ns/op	       1 B/op	       1 allocs/op
BenchmarkMatchString-16    	24261463	        51.16 ns/op	       0 B/op	       0 allocs/op

Signed-off-by: Eng Zer Jun <[email protected]>
@coreybutler coreybutler merged commit a73ef54 into coreybutler:master Oct 10, 2023
@coreybutler
Copy link
Owner

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants