Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
Oct 23, 2023
Merged

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

merged 1 commit into from
Oct 23, 2023

Commits on Oct 23, 2023

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

    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 allowedOrigin = regexp.MustCompile(".*.example.com")
    
    func BenchmarkMatch(b *testing.B) {
    	for i := 0; i < b.N; i++ {
    		if match := allowedOrigin.Match([]byte("www.example.com")); !match {
    			b.Fail()
    		}
    	}
    }
    
    func BenchmarkMatchString(b *testing.B) {
    	for i := 0; i < b.N; i++ {
    		if match := allowedOrigin.MatchString("wwww.example.com"); !match {
    			b.Fail()
    		}
    	}
    }
    
    goos: linux
    goarch: amd64
    pkg: github.com/gotify/server/v2/api/stream
    cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics
    BenchmarkMatch-16          	 2076819	       647.7 ns/op	      16 B/op	       1 allocs/op
    BenchmarkMatchString-16    	 2536326	       442.0 ns/op	       0 B/op	       0 allocs/op
    PASS
    ok  	github.com/gotify/server/v2/api/stream	3.552s
    
    Signed-off-by: Eng Zer Jun <[email protected]>
    Juneezee committed Oct 23, 2023
    Configuration menu
    Copy the full SHA
    ec3e140 View commit details
    Browse the repository at this point in the history