Skip to content

Instantly share code, notes, and snippets.

@dunglas
Created November 13, 2025 10:48
Show Gist options
  • Select an option

  • Save dunglas/653aedeaafdb2afc340d2a0d33201164 to your computer and use it in GitHub Desktop.

Select an option

Save dunglas/653aedeaafdb2afc340d2a0d33201164 to your computer and use it in GitHub Desktop.
Benchmark access to context.Context.Value VS method call
package benchmark_context_value
import (
"context"
"testing"
)
type contextKey struct{}
var ctxKey contextKey
type foo struct {
val string
}
func (f *foo) value() string {
return f.val
}
func BenchmarkContextValue(b *testing.B) {
ctx := context.WithValue(b.Context(), ctxKey, "value")
for b.Loop() {
ctx.Value(ctxKey)
}
}
func BenchmarkFunctionCall(b *testing.B) {
f := &foo{"value"}
for b.Loop() {
f.value()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment