Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid unnecessary byte/string conversion #1049

Merged
merged 1 commit into from
Oct 10, 2023
Merged

Avoid unnecessary byte/string conversion #1049

merged 1 commit into from
Oct 10, 2023

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 <engzerjun@gmail.com>
@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