Skip to content

Commit

Permalink
perf: avoid allocations with (*regexp.Regexp).MatchString (#3881)
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 := branchRegex.Match([]byte("main")); !match {
			b.Fail()
		}
	}
}

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

goos: linux
goarch: amd64
pkg: github.com/runatlantis/atlantis/server/core/config
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 8269699	       141.4 ns/op	       4 B/op	       1 allocs/op
BenchmarkMatchString-16    	14298446	        95.81 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/runatlantis/atlantis/server/core/config	2.784s

Signed-off-by: Eng Zer Jun <[email protected]>
Co-authored-by: PePe Amengual <[email protected]>
  • Loading branch information
Juneezee and jamengual committed Nov 15, 2023
1 parent 57fdc5a commit fd600d3
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion server/core/config/parser_validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func (p *ParserValidator) ParseRepoCfgData(repoCfgData []byte, globalCfg valid.G
//
i := 0
for _, p := range validConfig.Projects {
if branch == "" || p.BranchRegex == nil || p.BranchRegex.Match([]byte(branch)) {
if branch == "" || p.BranchRegex == nil || p.BranchRegex.MatchString(branch) {
validConfig.Projects[i] = p
i++
}
Expand Down

0 comments on commit fd600d3

Please sign in to comment.