Created
November 13, 2025 10:48
-
-
Save dunglas/653aedeaafdb2afc340d2a0d33201164 to your computer and use it in GitHub Desktop.
Benchmark access to context.Context.Value VS method call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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