Skip to content

Instantly share code, notes, and snippets.

@joesis
Created January 9, 2020 08:51
Show Gist options
  • Save joesis/c09aeeea9de62ba0233a4a8568a58720 to your computer and use it in GitHub Desktop.
Save joesis/c09aeeea9de62ba0233a4a8568a58720 to your computer and use it in GitHub Desktop.
Demonstrate the difference between several values and map as value
package proxy
import (
"context"
"testing"
)
// Benchmark2Context-4 5373907 192 ns/op
// Benchmark10Context-4 678060 1493 ns/op
// Benchmark20Context-4 289543 4408 ns/op
// Benchmark2KV-4 5133241 217 ns/op
// Benchmark10KV-4 1185910 1026 ns/op
// Benchmark20KV-4 502714 2392 ns/op
func simulate(n int) {
ctx := context.Background()
for i := 0; i < n; i++ {
ctx = context.WithValue(ctx, i, i)
}
for i := 0; i < n; i++ {
_ = ctx.Value(i)
}
}
func simulateKV(n int) {
ctx := context.Background()
kv := make(map[int]int)
for i := 0; i < n; i++ {
kv[i] = i
}
ctx = context.WithValue(ctx, "kv", kv)
for i := 0; i < n; i++ {
_ = ctx.Value("kv").(map[int]int)[i]
}
}
func Benchmark2Context(b *testing.B) {
for i := 0; i < b.N; i++ {
simulate(2)
}
}
func Benchmark10Context(b *testing.B) {
for i := 0; i < b.N; i++ {
simulate(10)
}
}
func Benchmark20Context(b *testing.B) {
for i := 0; i < b.N; i++ {
simulate(20)
}
}
func Benchmark2KV(b *testing.B) {
for i := 0; i < b.N; i++ {
simulateKV(2)
}
}
func Benchmark10KV(b *testing.B) {
for i := 0; i < b.N; i++ {
simulateKV(10)
}
}
func Benchmark20KV(b *testing.B) {
for i := 0; i < b.N; i++ {
simulateKV(20)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment