Skip to content

Instantly share code, notes, and snippets.

@gaby
Last active March 26, 2025 12:13
Show Gist options
  • Save gaby/5a390339b759f59284d26be11db4a532 to your computer and use it in GitHub Desktop.
Save gaby/5a390339b759f59284d26be11db4a532 to your computer and use it in GitHub Desktop.
Golang net/http benchmarks
package benchmark
import (
"net/http"
"testing"
)
// nopResponseWriter is a minimal implementation of http.ResponseWriter that does nothing.
type nopResponseWriter struct{}
func (n *nopResponseWriter) Header() http.Header {
return http.Header{}
}
func (n *nopResponseWriter) Write(b []byte) (int, error) {
return len(b), nil
}
func (n *nopResponseWriter) WriteHeader(statusCode int) {}
// Benchmark_Router_Next_Default benchmarks the sequential handling of a pre-created request.
func Benchmark_Router_Next_Default_NetHTTP(b *testing.B) {
// Create a new ServeMux and register a no-op handler for the "/" route.
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// no-op handler
})
handler := http.Handler(mux)
// Pre-create a base request and response writer.
req, _ := http.NewRequest(http.MethodGet, "/", nil)
nrw := &nopResponseWriter{}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
handler.ServeHTTP(nrw, req)
}
}
// Benchmark_Router_Next_Default_Parallel benchmarks handling in parallel.
func Benchmark_Router_Next_Default_Parallel_NetHTTP(b *testing.B) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// no-op handler
})
handler := http.Handler(mux)
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
// Create a new request for each parallel worker.
req, _ := http.NewRequest(http.MethodGet, "/", nil)
nrw := &nopResponseWriter{}
for pb.Next() {
// Create a new response writer for each call to avoid data races.
handler.ServeHTTP(nrw, req)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment