Skip to content

Commit f024e39

Browse files
korzhaogopherbot
authored andcommitted
reflect: optimize DeepEqual() for maps
benchmark old ns/op new ns/op delta BenchmarkMapsDeepEqual-10 235 200 -15.05% benchmark old allocs new allocs delta BenchmarkMapsDeepEqual-10 7 6 -14.29% benchmark old bytes new bytes delta BenchmarkMapsDeepEqual-10 96 48 -50.00% Change-Id: Ifa625ad25524cc9ee438711917606626b33a9597 Reviewed-on: https://go-review.googlesource.com/c/go/+/512576 TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: David Chase <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent c17e0cd commit f024e39

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

src/reflect/benchmark_test.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,18 @@ func BenchmarkDeepEqual(b *testing.B) {
107107
}
108108
}
109109

110+
func BenchmarkMapsDeepEqual(b *testing.B) {
111+
m1 := map[int]int{
112+
1: 1, 2: 2,
113+
}
114+
m2 := map[int]int{
115+
1: 1, 2: 2,
116+
}
117+
for i := 0; i < b.N; i++ {
118+
DeepEqual(m1, m2)
119+
}
120+
}
121+
110122
func BenchmarkIsZero(b *testing.B) {
111123
source := ValueOf(struct {
112124
ArrayComparable [4]T

src/reflect/deepequal.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -142,9 +142,10 @@ func deepValueEqual(v1, v2 Value, visited map[visit]bool) bool {
142142
if v1.UnsafePointer() == v2.UnsafePointer() {
143143
return true
144144
}
145-
for _, k := range v1.MapKeys() {
146-
val1 := v1.MapIndex(k)
147-
val2 := v2.MapIndex(k)
145+
iter := v1.MapRange()
146+
for iter.Next() {
147+
val1 := iter.Value()
148+
val2 := v2.MapIndex(iter.Key())
148149
if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(val1, val2, visited) {
149150
return false
150151
}

0 commit comments

Comments
 (0)