From 0bfa5ca4d964161252c9a110aec53ca00c6f684b Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Mon, 23 Oct 2023 23:57:15 +0800 Subject: [PATCH] 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 --- api/stream/stream.go | 2 +- auth/cors.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/api/stream/stream.go b/api/stream/stream.go index 5e8692f75..9ad54ee0d 100644 --- a/api/stream/stream.go +++ b/api/stream/stream.go @@ -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 } } diff --git a/auth/cors.go b/auth/cors.go index ebf2afebd..3cfb1fedc 100644 --- a/auth/cors.go +++ b/auth/cors.go @@ -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 } }