]> Cypherpunks repositories - gostls13.git/commitdiff
reflect: optimize DeepEqual() for maps
authorkorzhao <korzhao95@gmail.com>
Thu, 6 Jul 2023 03:12:29 +0000 (11:12 +0800)
committerGopher Robot <gobot@golang.org>
Mon, 31 Jul 2023 15:44:01 +0000 (15:44 +0000)
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 <gobot@golang.org>
Reviewed-by: David Chase <drchase@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
Run-TryBot: Ian Lance Taylor <iant@golang.org>

src/reflect/benchmark_test.go
src/reflect/deepequal.go

index 9241c2c3d3d9e9d6b12fbaa8b6665c80b957089f..b499ad71220326f3f8784e01721e73b01ed9d649 100644 (file)
@@ -107,6 +107,18 @@ func BenchmarkDeepEqual(b *testing.B) {
        }
 }
 
+func BenchmarkMapsDeepEqual(b *testing.B) {
+       m1 := map[int]int{
+               1: 1, 2: 2,
+       }
+       m2 := map[int]int{
+               1: 1, 2: 2,
+       }
+       for i := 0; i < b.N; i++ {
+               DeepEqual(m1, m2)
+       }
+}
+
 func BenchmarkIsZero(b *testing.B) {
        source := ValueOf(struct {
                ArrayComparable    [4]T
index 579781e7038f3e351fe0d1cdb5f2903455816fea..961e17011839bd58b72ec29f6a8a70d1a5b33307 100644 (file)
@@ -142,9 +142,10 @@ func deepValueEqual(v1, v2 Value, visited map[visit]bool) bool {
                if v1.UnsafePointer() == v2.UnsafePointer() {
                        return true
                }
-               for _, k := range v1.MapKeys() {
-                       val1 := v1.MapIndex(k)
-                       val2 := v2.MapIndex(k)
+               iter := v1.MapRange()
+               for iter.Next() {
+                       val1 := iter.Value()
+                       val2 := v2.MapIndex(iter.Key())
                        if !val1.IsValid() || !val2.IsValid() || !deepValueEqual(val1, val2, visited) {
                                return false
                        }