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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 |
package main
// go test -v cmp_test.go -bench "Benchmark" -benchmem
import (
"reflect"
"testing"
"github.com/google/go-cmp/cmp"
)
type T struct {
X int
Y string
Z []int
M map[string]string
}
var (
t1 = T{
X: 1,
Y: "lei",
Z: []int{1, 2, 3},
M: map[string]string{
"a": "111112222",
"c": "9",
"b": "2222",
},
}
t2 = T{
X: 1,
Y: "lei",
Z: []int{1, 2, 3},
M: map[string]string{
"a": "111112222",
"c": "9",
"b": "3333",
},
}
)
func customEqual(t1, t2 T) bool {
if t1.X != t2.X {
return false
}
if t1.Y != t2.Y {
return false
}
if len(t1.Z) != len(t2.Z) {
return false
}
for i, v := range t1.Z {
if t2.Z[i] != v {
return false
}
}
if len(t1.M) != len(t2.M) {
return false
}
for k := range t1.M {
if t2.M[k] != t1.M[k] {
return false
}
}
return true
}
func customEqual2(t1, t2 T) bool {
if t1.X != t2.X {
return false
}
if t1.Y != t2.Y {
return false
}
if len(t1.Z) != len(t2.Z) {
return false
}
for i, v := range t1.Z {
if t2.Z[i] != v {
return false
}
}
if len(t1.M) != len(t2.M) {
return false
}
for k := range t1.M {
if t2.M[k] != t1.M[k] {
return false
}
}
return true
}
func Benchmark_reflect_DeepEqual(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
reflect.DeepEqual(t2, t1)
}
}
func Benchmark_cmp_Equal(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
cmp.Equal(t2, t1)
}
}
func Benchmark_custom_Equal(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
customEqual(t2, t1)
}
}
|