-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbench_test.go
104 lines (90 loc) · 2.1 KB
/
bench_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package fcontext_test
import (
"context"
"fmt"
"testing"
"github.com/posener/fcontext"
)
type withValue func(context.Context, interface{}, interface{}) context.Context
var values = []int{
10,
100,
1000,
}
func Benchmark(b *testing.B) {
b.Run("fcontext", func(b *testing.B) { runBenchmarks(b, fcontext.WithValue) })
b.Run("stdctx", func(b *testing.B) { runBenchmarks(b, context.WithValue) })
}
func runBenchmarks(b *testing.B, wv withValue) {
benchmarks := []struct {
name string
fn func(*testing.B, withValue)
}{
{"WithValue/Depth", withValueNested},
{"WithValue/Breadth", withValueShallow},
{"Value/DifferentKeys", valueDifferentKeys},
{"Value/SameKey", valueSameKey},
}
for _, bench := range benchmarks {
b.Run(bench.name, func(b *testing.B) {
bench.fn(b, wv)
})
}
}
func withValueShallow(b *testing.B, withValue withValue) {
ctx := context.Background()
for i := 0; i < b.N; i++ {
withValue(ctx, i, i)
}
}
func withValueNested(b *testing.B, withValue withValue) {
ctx := context.Background()
for i := 0; i < b.N; i++ {
ctx = withValue(ctx, i, i)
}
}
func valueDifferentKeys(b *testing.B, withValue withValue) {
ctx := context.Background()
for _, value := range values {
b.Run(fmt.Sprintf("%dKeys", value), func(b *testing.B) {
for i := 0; i < value; i++ {
ctx = withValue(ctx, i, i)
}
b.Run("Average", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for j := 0; j < value; j++ {
_ = ctx.Value(j)
}
}
})
b.Run("Latest", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ctx.Value(value - 1)
}
})
b.Run("Earliest", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ctx.Value(0)
}
})
b.Run("NotFound", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ctx.Value(value)
}
})
})
}
}
func valueSameKey(b *testing.B, withValue withValue) {
ctx := context.Background()
for _, value := range values {
for i := 0; i < value; i++ {
ctx = withValue(ctx, 0, 0)
}
b.Run(fmt.Sprintf("%dKeys", value), func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = ctx.Value(0)
}
})
}
}