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 #602

Merged
merged 1 commit into from
Oct 29, 2023
Merged

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

merged 1 commit into from
Oct 29, 2023

Conversation

Juneezee
Copy link

What does this do?

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 := timeWithSeconds.Match([]byte("06:18:01")); !match {
			b.Fail()
		}
	}
}

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

Result:

goos: linux
goarch: amd64
pkg: github.com/go-co-op/gocron
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 7213512	       223.8 ns/op	       8 B/op	       1 allocs/op
BenchmarkMatchString-16    	 8484169	       145.8 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/go-co-op/gocron	4.114s

Which issue(s) does this PR fix/relate to?

List any changes that modify/break current functionality

Have you included tests for your changes?

Did you document any new/modified functionality?

  • Updated example_test.go
  • Updated README.md

Notes

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 := timeWithSeconds.Match([]byte("06:18:01")); !match {
			b.Fail()
		}
	}
}

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

goos: linux
goarch: amd64
pkg: github.com/go-co-op/gocron
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 7213512	       223.8 ns/op	       8 B/op	       1 allocs/op
BenchmarkMatchString-16    	 8484169	       145.8 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/go-co-op/gocron	4.114s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
@JohnRoesler JohnRoesler merged commit 12cfd7a into go-co-op:v1 Oct 29, 2023
6 checks passed
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