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:

var excludeRegex = regexp.MustCompile("vendor")

func BenchmarkMatch(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := excludeRegex.Match([]byte("vendor/pkg/main.go")); !match {
			b.Fail()
		}
	}
}

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

goos: linux
goarch: amd64
pkg: github.com/boyter/scc/v3/processor
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 4123592	       274.9 ns/op	      24 B/op	       1 allocs/op
BenchmarkMatchString-16    	 7006401	       145.1 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/boyter/scc/v3/processor	2.637s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
  • Loading branch information
Juneezee committed Nov 5, 2023
1 parent a960adc commit c1708af
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion processor/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ DIRENTS:
}

for _, exclude := range dw.excludes {
if exclude.Match([]byte(name)) || exclude.Match([]byte(path)) {
if exclude.MatchString(name) || exclude.MatchString(path) {
if Verbose {
printWarn("skipping file/directory due to match exclude: " + name)
}
Expand Down

0 comments on commit c1708af

Please sign in to comment.