-
Notifications
You must be signed in to change notification settings - Fork 1
/
reflect_bench_test.go
81 lines (68 loc) · 1.73 KB
/
reflect_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
package pocket_test
import (
"os"
"reflect"
"testing"
)
type P struct {
A string
B string
}
func handler(props P) error {
return nil
}
var arg = P{A: "one", B: "two"}
var handlerV reflect.Value
var handlerT reflect.Type
var handlerI interface{}
var argV reflect.Value
var argT reflect.Type
func TestMain(m *testing.M) {
handlerV = reflect.ValueOf(handler)
handlerT = reflect.TypeOf(handler)
handlerI = handlerV.Interface()
argV = reflect.ValueOf(arg)
argT = handlerT.In(0)
os.Exit(m.Run())
}
// This is how calls are done by the library at the moment.
// It's quite slow unfortunately...
func BenchmarkReflectCall(b *testing.B) {
for n := 0; n < b.N; n++ {
handlerV.Call([]reflect.Value{argV})
}
}
// This is a normal function call for reference. It's fast, obviously!
func BenchmarkFunctionCall(b *testing.B) {
for n := 0; n < b.N; n++ {
handler(arg)
}
}
// This is an alternative way of doing a call, unfortunately it requires a type
// assertion so this cannot be automated by the library. Any interface that
// would require this, would require the user to explicitly specify this
// *somewhere*... (not sure where yet...)
func BenchmarkFunctionInterfaceCastCall(b *testing.B) {
for n := 0; n < b.N; n++ {
handlerI.(func(P) error)(arg)
}
}
// Some struct access benchmarks
func BenchmarkNumFieldsType(b *testing.B) {
type T struct {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z string
}
TT := reflect.TypeOf(T{})
for n := 0; n < b.N; n++ {
TT.NumField()
}
}
func BenchmarkNumFieldsValue(b *testing.B) {
type T struct {
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z string
}
TV := reflect.ValueOf(T{})
for n := 0; n < b.N; n++ {
TV.NumField()
}
}