]> Cypherpunks repositories - gostls13.git/commitdiff
container/heap: optimization in case heap has many duplicates
authorTaj Khattra <taj.khattra@gmail.com>
Wed, 10 Oct 2012 18:35:57 +0000 (11:35 -0700)
committerRobert Griesemer <gri@golang.org>
Wed, 10 Oct 2012 18:35:57 +0000 (11:35 -0700)
benchmark       old ns/op    new ns/op    delta
BenchmarkDup      3075682       609448  -80.18%

R=gri
CC=golang-dev
https://golang.org/cl/6613064

src/pkg/container/heap/heap.go
src/pkg/container/heap/heap_test.go

index 67018e6baea929887e3812109450be96dadb87a1..bbaf40a989d5c26378b8a12792ce4a80476df309 100644 (file)
@@ -79,7 +79,7 @@ func Remove(h Interface, i int) interface{} {
 func up(h Interface, j int) {
        for {
                i := (j - 1) / 2 // parent
-               if i == j || h.Less(i, j) {
+               if i == j || !h.Less(j, i) {
                        break
                }
                h.Swap(i, j)
@@ -97,7 +97,7 @@ func down(h Interface, i, n int) {
                if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) {
                        j = j2 // = 2*i + 2  // right child
                }
-               if h.Less(i, j) {
+               if !h.Less(j, i) {
                        break
                }
                h.Swap(i, j)
index cb31ef6d30ab3e1c9c90c2484c500627381e9752..73f33e8d2cfc7067c2a4cd83fbcb22b1a0e1ee8f 100644 (file)
@@ -170,3 +170,16 @@ func TestRemove2(t *testing.T) {
                }
        }
 }
+
+func BenchmarkDup(b *testing.B) {
+       const n = 10000
+       h := make(myHeap, n)
+       for i := 0; i < b.N; i++ {
+               for j := 0; j < n; j++ {
+                       Push(&h, 0) // all elements are the same
+               }
+               for h.Len() > 0 {
+                       Pop(&h)
+               }
+       }
+}