Skip to content

Commit 2ce295e

Browse files
committed
net/http: remove an allocation in ServeMux
Also, add a benchmark variant ("SkipServe") that only benchmarks the ServeMux handler selection path. name old time/op new time/op delta ServeMux_SkipServe-4 74.2µs ± 2% 60.6µs ± 1% -18.31% (p=0.000 n=10+9) name old alloc/op new alloc/op delta ServeMux_SkipServe-4 2.62kB ± 0% 0.00kB ±NaN% -100.00% (p=0.000 n=10+10) name old allocs/op new allocs/op delta ServeMux_SkipServe-4 180 ± 0% 0 ±NaN% -100.00% (p=0.000 n=10+10) Updates #25383 Change-Id: Icfbb3b977e309093d032e922d1b4f254df6f5955 Reviewed-on: https://go-review.googlesource.com/116378 Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Emmanuel Odeke <[email protected]>
1 parent ebb8a1f commit 2ce295e

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

src/net/http/serve_test.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -608,8 +608,9 @@ func TestShouldRedirectConcurrency(t *testing.T) {
608608
mux.HandleFunc("/", func(w ResponseWriter, r *Request) {})
609609
}
610610

611-
func BenchmarkServeMux(b *testing.B) {
612-
611+
func BenchmarkServeMux(b *testing.B) { benchmarkServeMux(b, true) }
612+
func BenchmarkServeMux_SkipServe(b *testing.B) { benchmarkServeMux(b, false) }
613+
func benchmarkServeMux(b *testing.B, runHandler bool) {
613614
type test struct {
614615
path string
615616
code int
@@ -641,9 +642,11 @@ func BenchmarkServeMux(b *testing.B) {
641642
for _, tt := range tests {
642643
*rw = httptest.ResponseRecorder{}
643644
h, pattern := mux.Handler(tt.req)
644-
h.ServeHTTP(rw, tt.req)
645-
if pattern != tt.path || rw.Code != tt.code {
646-
b.Fatalf("got %d, %q, want %d, %q", rw.Code, pattern, tt.code, tt.path)
645+
if runHandler {
646+
h.ServeHTTP(rw, tt.req)
647+
if pattern != tt.path || rw.Code != tt.code {
648+
b.Fatalf("got %d, %q, want %d, %q", rw.Code, pattern, tt.code, tt.path)
649+
}
647650
}
648651
}
649652
}

src/net/http/server.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2182,7 +2182,12 @@ func cleanPath(p string) string {
21822182
// path.Clean removes trailing slash except for root;
21832183
// put the trailing slash back if necessary.
21842184
if p[len(p)-1] == '/' && np != "/" {
2185-
np += "/"
2185+
// Fast path for common case of p being the string we want:
2186+
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
2187+
np = p
2188+
} else {
2189+
np += "/"
2190+
}
21862191
}
21872192
return np
21882193
}

0 commit comments

Comments
 (0)