Skip to content

Commit

Permalink
perf: 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 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>
  • Loading branch information
Juneezee committed Oct 23, 2023
1 parent 92916f0 commit ec3e140
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 2 deletions.
2 changes: 1 addition & 1 deletion api/stream/stream.go
Expand Up @@ -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
}
}
Expand Down
2 changes: 1 addition & 1 deletion auth/cors.go
Expand Up @@ -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
}
}
Expand Down

0 comments on commit ec3e140

Please sign in to comment.