mgechev / revive

🔥 ~6x faster, stricter, configurable, extensible, and beautiful drop-in replacement for golint
https://revive.run
MIT License
4.69k stars 273 forks source link

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

Closed Juneezee closed 8 months ago

Juneezee commented 8 months ago

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
chavacava commented 8 months ago

Thank you @Juneezee, nice catch!