Skip to content

Commit

Permalink
Update benchmark
Browse files Browse the repository at this point in the history
Also initialize the response headers with the default header in
benchmarks as all reponse at least have one header. This removes the
single allocation that should not be attributed to this library.

Also add a micro-optimization on the critical path.
  • Loading branch information
rs committed Feb 9, 2024
1 parent eacc8e8 commit 0bcf73f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 12 deletions.
16 changes: 8 additions & 8 deletions README.md
Expand Up @@ -106,15 +106,15 @@ See [API documentation](http://godoc.org/github.com/rs/cors) for more info.
goos: darwin
goarch: arm64
pkg: github.com/rs/cors
BenchmarkWithout-10 352671961 3.317 ns/op 0 B/op 0 allocs/op
BenchmarkDefault-10 18261723 65.63 ns/op 0 B/op 0 allocs/op
BenchmarkAllowedOrigin-10 13309591 90.21 ns/op 0 B/op 0 allocs/op
BenchmarkPreflight-10 7247728 166.9 ns/op 0 B/op 0 allocs/op
BenchmarkPreflightHeader-10 5915437 202.9 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/match-10 250336476 4.784 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/too_short-10 1000000000 0.6354 ns/op 0 B/op 0 allocs/op
BenchmarkWithout-10 135325480 8.124 ns/op 0 B/op 0 allocs/op
BenchmarkDefault-10 24082140 51.40 ns/op 0 B/op 0 allocs/op
BenchmarkAllowedOrigin-10 16424518 88.25 ns/op 0 B/op 0 allocs/op
BenchmarkPreflight-10 8010259 147.3 ns/op 0 B/op 0 allocs/op
BenchmarkPreflightHeader-10 6850962 175.0 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/match-10 253275342 4.714 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/too_short-10 1000000000 0.6235 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/rs/cors 9.613s
ok github.com/rs/cors 99.131s
```

## Licenses
Expand Down
4 changes: 3 additions & 1 deletion bench_test.go
Expand Up @@ -100,7 +100,9 @@ func BenchmarkPreflightHeader(b *testing.B) {
func makeFakeResponses(n int) []*FakeResponse {
resps := make([]*FakeResponse, n)
for i := 0; i < n; i++ {
resps[i] = &FakeResponse{http.Header{}}
resps[i] = &FakeResponse{http.Header{
"Content-Type": []string{"text/plain"},
}}
}
return resps
}
6 changes: 3 additions & 3 deletions cors.go
Expand Up @@ -394,10 +394,10 @@ func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {
allowed, additionalVaryHeaders := c.isOriginAllowed(r, origin)

// Always set Vary, see https://github.com/rs/cors/issues/10
if vary, found := headers["Vary"]; found {
headers["Vary"] = append(vary, headerVaryOrigin[0])
} else {
if vary := headers["Vary"]; vary == nil {
headers["Vary"] = headerVaryOrigin
} else {
headers["Vary"] = append(vary, headerVaryOrigin[0])
}
if len(additionalVaryHeaders) > 0 {
headers.Add("Vary", strings.Join(convert(additionalVaryHeaders, http.CanonicalHeaderKey), ", "))
Expand Down

0 comments on commit 0bcf73f

Please sign in to comment.