onsi / ginkgo

A Modern Testing Framework for Go
http://onsi.github.io/ginkgo/
MIT License
8.12k stars 644 forks source link

Avoid allocations with `(*regexp.Regexp).MatchString` #1302

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:

var goTestRegExp = regexp.MustCompile(`_test\.go$`)

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

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

Result:

goos: linux
goarch: amd64
pkg: github.com/onsi/ginkgo/v2/ginkgo/watch
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16            5665784           314.4 ns/op        16 B/op          1 allocs/op
BenchmarkMatchString-16      8481872           140.5 ns/op         0 B/op          0 allocs/op
PASS
ok      github.com/onsi/ginkgo/v2/ginkgo/watch  4.321s
onsi commented 8 months ago

SGTM thanks!