grafana / k6

A modern load testing tool, using Go and JavaScript - https://k6.io
GNU Affero General Public License v3.0
26.13k stars 1.27k forks source link

metrics: use `regexp.MatchString` for metric name check #4047

Closed Juneezee closed 1 week ago

Juneezee commented 2 weeks ago

What?

(*Regexp).Match have a string-based equivalent (*Regexp).MatchString. We should use the string version to avoid unnecessary []byte conversions.

Why?

It's a one-line change that provides a free performance gain.

Benchmark:

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

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

Result:

goos: linux
goarch: amd64
pkg: go.k6.io/k6/metrics
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16            1457095           820.7 ns/op        16 B/op          1 allocs/op
BenchmarkMatchString-16      1664458           726.6 ns/op         0 B/op          0 allocs/op
PASS
coverage: 0.2% of statements
ok      go.k6.io/k6/metrics 3.983s

Checklist

Related PR(s)/Issue(s)