-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathperf_test.go
71 lines (58 loc) · 1.26 KB
/
perf_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
package module
import (
"context"
"testing"
)
type DB struct {
target string
}
func NewDB(ctx context.Context) (*DB, error) {
return &DB{
target: "localhost.db",
}, nil
}
type Cache struct {
fallback *DB
}
func NewCache(ctx context.Context) (*Cache, error) {
db := moduleDB.Value(ctx)
return &Cache{
fallback: db,
}, nil
}
var (
moduleDB = New[*DB]()
moduleCache = New[*Cache]()
provideDB = moduleDB.ProvideWithFunc(NewDB)
provideCache = moduleCache.ProvideWithFunc(NewCache)
)
func BenchmarkThroughModuleValue(b *testing.B) {
repo := NewRepo()
repo.Add(provideDB)
repo.Add(provideCache)
ctx, err := repo.InjectTo(context.Background())
if err != nil {
b.Fatal("create context error:", err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var _ *Cache = moduleCache.Value(ctx)
}
}
func BenchmarkSimpleContextValue(b *testing.B) {
ctx := context.Background()
db, err := NewDB(ctx)
if err != nil {
b.Fatal("create db error:", err)
}
ctx = context.WithValue(ctx, moduleDB.moduleKey, db)
cache, err := NewCache(ctx)
if err != nil {
b.Fatal("create cache error:", err)
}
ctx = context.WithValue(ctx, moduleCache.moduleKey, cache)
b.ResetTimer()
for i := 0; i < b.N; i++ {
var _ *Cache = ctx.Value(moduleCache.moduleKey).(*Cache)
}
}