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

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 <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun
2023-10-23 23:57:15 +08:00
committed by GitHub
parent 92916f0117
commit 0bfa5ca4d9
2 changed files with 2 additions and 2 deletions

View File

@@ -196,7 +196,7 @@ func isAllowedOrigin(r *http.Request, allowedOrigins []*regexp.Regexp) bool {
}
for _, allowedOrigin := range allowedOrigins {
if allowedOrigin.Match([]byte(strings.ToLower(u.Hostname()))) {
if allowedOrigin.MatchString(strings.ToLower(u.Hostname())) {
return true
}
}

View File

@@ -29,7 +29,7 @@ func CorsConfig(conf *config.Configuration) cors.Config {
corsConf.AllowHeaders = conf.Server.Cors.AllowHeaders
corsConf.AllowOriginFunc = func(origin string) bool {
for _, compiledOrigin := range compiledOrigins {
if compiledOrigin.Match([]byte(strings.ToLower(origin))) {
if compiledOrigin.MatchString(strings.ToLower(origin)) {
return true
}
}