Skip to content

Commit 0db2505

Browse files
committed
tests: refactor benchmarks to remove test server overhead
The httptest Server introduces unrelated overhead to the benchmarks. Ideally we'd only measure the impact on the wrapped handler.
1 parent ef9fc62 commit 0db2505

1 file changed

Lines changed: 18 additions & 13 deletions

File tree

bench_test.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,15 @@ import (
77
)
88

99
func BenchmarkBaseline(b *testing.B) {
10-
benchmark(b, false)
10+
benchmark(b, 0)
1111
}
1212

1313
func BenchmarkCaptureMetrics(b *testing.B) {
14-
benchmark(b, true)
14+
benchmark(b, 1)
15+
}
16+
17+
func BenchmarkCaptureMetricsTwice(b *testing.B) {
18+
benchmark(b, 2)
1519
}
1620

1721
func BenchmarkWrap(b *testing.B) {
@@ -32,22 +36,23 @@ func BenchmarkWrap(b *testing.B) {
3236
<-doneCh
3337
}
3438

35-
func benchmark(b *testing.B, captureMetrics bool) {
36-
b.StopTimer()
39+
func benchmark(b *testing.B, wrappings int) {
3740
dummyH := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})
3841
h := dummyH
39-
if captureMetrics {
42+
for x := 0; x < wrappings; x++ {
43+
hCopy := h
4044
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
41-
CaptureMetrics(dummyH, w, r)
45+
CaptureMetrics(hCopy, w, r)
4246
})
4347
}
44-
s := httptest.NewServer(h)
45-
defer s.Close()
46-
b.StartTimer()
48+
49+
req := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
50+
resp := httptest.NewRecorder() // ok to reuse; we're not writing anything to it
51+
52+
b.ReportAllocs()
53+
b.ResetTimer()
54+
4755
for i := 0; i < b.N; i++ {
48-
_, err := http.Get(s.URL)
49-
if err != nil {
50-
b.Fatal(err)
51-
}
56+
h.ServeHTTP(resp, req)
5257
}
5358
}

0 commit comments

Comments
 (0)