Skip to content
New issue

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

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

Already on GitHub? # to your account

var-naming: avoid allocations with (*regexp.Regexp).MatchString #928

Merged
merged 1 commit into from
Nov 2, 2023
Merged

var-naming: avoid allocations with (*regexp.Regexp).MatchString #928

merged 1 commit into from
Nov 2, 2023

Conversation

Juneezee
Copy link
Contributor

@Juneezee Juneezee commented Nov 1, 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 := upperCaseConstRE.Match([]byte("FOO_BAR")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := upperCaseConstRE.MatchString("FOO_BAR"); !match {
			b.Fail()
		}
	}
}
goos: linux
goarch: amd64
pkg: github.com/mgechev/revive/rule
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 5248138	       285.8 ns/op	       8 B/op	       1 allocs/op
BenchmarkMatchString-16    	 6899334	       170.9 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/mgechev/revive/rule	4.102s

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

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

goos: linux
goarch: amd64
pkg: github.com/mgechev/revive/rule
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 5248138	       285.8 ns/op	       8 B/op	       1 allocs/op
BenchmarkMatchString-16    	 6899334	       170.9 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/mgechev/revive/rule	4.102s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
@chavacava chavacava merged commit 573f715 into mgechev:master Nov 2, 2023
@chavacava
Copy link
Collaborator

Thank you @Juneezee, nice catch!

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants