Skip to content

Commit

Permalink
perf: avoid allocations with (*regexp.Regexp).MatchString (gitleaks…
Browse files Browse the repository at this point in the history
…#1283)

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:

var pathRegex = regexp.MustCompile(".*.yaml")

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

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := pathRegex.MatchString("./config/deploy.yaml"); !match {
			b.Fail()
		}
	}
}

goos: linux
goarch: amd64
pkg: github.com/zricethezav/gitleaks/v8/detect
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 2167712	       657.9 ns/op	      24 B/op	       1 allocs/op
BenchmarkMatchString-16    	 3275372	       324.8 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/zricethezav/gitleaks/v8/detect	3.436s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
  • Loading branch information
Juneezee authored Oct 28, 2023
1 parent a3ab4e8 commit b496677
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions detect/detect.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find

if rule.Path != nil && rule.Regex == nil {
// Path _only_ rule
if rule.Path.Match([]byte(fragment.FilePath)) {
if rule.Path.MatchString(fragment.FilePath) {
finding := report.Finding{
Description: rule.Description,
File: fragment.FilePath,
Expand All @@ -235,7 +235,7 @@ func (d *Detector) detectRule(fragment Fragment, rule config.Rule) []report.Find
// if path is set _and_ a regex is set, then we need to check both
// so if the path does not match, then we should return early and not
// consider the regex
if !rule.Path.Match([]byte(fragment.FilePath)) {
if !rule.Path.MatchString(fragment.FilePath) {
return findings
}
}
Expand Down

0 comments on commit b496677

Please sign in to comment.