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

perf: avoid allocations with (*regexp.Regexp).MatchString #930

Merged
merged 1 commit into from Nov 3, 2023
Merged

perf: avoid allocations with (*regexp.Regexp).MatchString #930

merged 1 commit into from Nov 3, 2023

Conversation

Juneezee
Copy link
Contributor

@Juneezee Juneezee commented Nov 3, 2023

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:

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

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

Result:

goos: linux
goarch: amd64
pkg: github.com/zincsearch/zincsearch/pkg/core
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 1530795	       776.2 ns/op	      32 B/op	       1 allocs/op
BenchmarkMatchString-16    	 2233713	       591.4 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/zincsearch/zincsearch/pkg/core	3.799s

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:

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

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

goos: linux
goarch: amd64
pkg: github.com/zincsearch/zincsearch/pkg/core
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 1530795	       776.2 ns/op	      32 B/op	       1 allocs/op
BenchmarkMatchString-16    	 2233713	       591.4 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/zincsearch/zincsearch/pkg/core	3.799s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
@hengfeiyang hengfeiyang merged commit deca6ed into zincsearch:main Nov 3, 2023
1 check passed
@hengfeiyang
Copy link
Contributor

@Juneezee Thanks for the improve.

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