Skip to content

perf: avoid allocations with (*regexp.Regexp).MatchString#1592

Merged
spiffcs merged 1 commit intoanchore:mainfrom
Juneezee:perf/regexp-matchstring
Nov 8, 2023
Merged

perf: avoid allocations with (*regexp.Regexp).MatchString#1592
spiffcs merged 1 commit intoanchore:mainfrom
Juneezee:perf/regexp-matchstring

Conversation

@Juneezee
Copy link
Copy Markdown
Contributor

@Juneezee Juneezee commented Nov 8, 2023

We should use (*regexp.Regexp).MatchString instead of (*regexp.Regexp).Match([]byte(...)) when matching string to avoid unnecessary []byte conversions and reduce allocations. A one-line change for free performance improvement.

Example benchmark:

func BenchmarkMatch(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := pseudoSemverPattern.Match([]byte("1.0.0-beta-prerelease")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := pseudoSemverPattern.MatchString("1.0.0-beta-prerelease"); !match {
			b.Fail()
		}
	}
}

Result:

goos: linux
goarch: amd64
pkg: github.com/anchore/grype/grype/version
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 1378789	       889.7 ns/op	      24 B/op	       1 allocs/op
BenchmarkMatchString-16    	 2287442	       482.2 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/anchore/grype/grype/version	3.632s

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 := pseudoSemverPattern.Match([]byte("1.0.0-beta-prerelease")); !match {
			b.Fail()
		}
	}
}

func BenchmarkMatchString(b *testing.B) {
	for i := 0; i < b.N; i++ {
		if match := pseudoSemverPattern.MatchString("1.0.0-beta-prerelease"); !match {
			b.Fail()
		}
	}
}

goos: linux
goarch: amd64
pkg: github.com/anchore/grype/grype/version
cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
BenchmarkMatch-16          	 1378789	       889.7 ns/op	      24 B/op	       1 allocs/op
BenchmarkMatchString-16    	 2287442	       482.2 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/anchore/grype/grype/version	3.632s

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
@spiffcs spiffcs merged commit 3c255e3 into anchore:main Nov 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants