From bc5c1784633bc914eafcd4f944b774c978fe857e Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Mon, 6 Nov 2023 22:38:29 +0800 Subject: [PATCH] Avoid allocations with `(*regexp.Regexp).MatchString` 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 := envVarNameRegexp.Match([]byte("FOO_BAR")); !match { b.Fail() } } } func BenchmarkMatchString(b *testing.B) { for i := 0; i < b.N; i++ { if match := envVarNameRegexp.MatchString("FOO_BAR"); !match { b.Fail() } } } goos: linux goarch: amd64 pkg: go.ddosify.com/ddosify/core/types cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkMatch-16 4542174 277.2 ns/op 8 B/op 1 allocs/op BenchmarkMatchString-16 7210927 172.1 ns/op 0 B/op 0 allocs/op PASS ok go.ddosify.com/ddosify/core/types 3.908s Signed-off-by: Eng Zer Jun --- core/types/scenario.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/types/scenario.go b/core/types/scenario.go index 7fb83c58..ed1d6e1e 100644 --- a/core/types/scenario.go +++ b/core/types/scenario.go @@ -86,7 +86,7 @@ func (s *Scenario) validate() error { // add global envs for key := range s.Envs { - if !envVarNameRegexp.Match([]byte(key)) { // not a valid env definition + if !envVarNameRegexp.MatchString(key) { // not a valid env definition return fmt.Errorf("env key is not valid: %s", key) } definedEnvs[key] = struct{}{} // exist @@ -98,7 +98,7 @@ func (s *Scenario) validate() error { return fmt.Errorf("csv key can not have dot in it: %s", key) } for _, s := range splitted { - if !envVarNameRegexp.Match([]byte(s)) { // not a valid env definition + if !envVarNameRegexp.MatchString(s) { // not a valid env definition return fmt.Errorf("csv key is not valid: %s", key) } } @@ -112,7 +112,7 @@ func (s *Scenario) validate() error { // enrich Envs map with captured envs from each step for _, ce := range st.EnvsToCapture { - if !envVarNameRegexp.Match([]byte(ce.Name)) { // not a valid env definition + if !envVarNameRegexp.MatchString(ce.Name) { // not a valid env definition return fmt.Errorf("captured env key is not valid: %s", ce.Name) } definedEnvs[ce.Name] = struct{}{}