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 allocations with (*regexp.Regexp).MatchString #1302

Merged
merged 1 commit into from Nov 11, 2023
Merged

Avoid allocations with (*regexp.Regexp).MatchString #1302

merged 1 commit into from Nov 11, 2023

Conversation

Juneezee
Copy link
Contributor

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

Example benchmark:

var goTestRegExp = regexp.MustCompile(`_test\.go$`)

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

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

Result:

goos: linux
goarch: amd64
pkg: github.com/onsi/ginkgo/v2/ginkgo/watch
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 5665784	       314.4 ns/op	      16 B/op	       1 allocs/op
BenchmarkMatchString-16    	 8481872	       140.5 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/onsi/ginkgo/v2/ginkgo/watch	4.321s

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

Example benchmark:

var goTestRegExp = regexp.MustCompile(`_test\.go$`)

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

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

goos: linux
goarch: amd64
pkg: github.com/onsi/ginkgo/v2/ginkgo/watch
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 5665784	       314.4 ns/op	      16 B/op	       1 allocs/op
BenchmarkMatchString-16    	 8481872	       140.5 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/onsi/ginkgo/v2/ginkgo/watch	4.321s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
@onsi onsi merged commit 3b2a2a7 into onsi:master Nov 11, 2023
6 checks passed
@onsi
Copy link
Owner

onsi commented Nov 11, 2023

SGTM 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.

None yet

2 participants