Skip to content

Commit

Permalink
Avoid allocations with (*regexp.Regexp).MatchString
Browse files Browse the repository at this point in the history
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 <engzerjun@gmail.com>
  • Loading branch information
Juneezee committed Nov 6, 2023
1 parent daeabc1 commit bc5c178
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions core/types/scenario.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
}
Expand All @@ -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{}{}
Expand Down

0 comments on commit bc5c178

Please sign in to comment.