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. A one-line change for free performance improvement.Example benchmark: