Commit c12dab2a authored by Taj Khattra's avatar Taj Khattra Committed by Robert Griesemer

container/heap: optimization in case heap has many duplicates

benchmark       old ns/op    new ns/op    delta
BenchmarkDup      3075682       609448  -80.18%

R=gri
CC=golang-dev
https://golang.org/cl/6613064
parent 4c9c36e6
...@@ -79,7 +79,7 @@ func Remove(h Interface, i int) interface{} { ...@@ -79,7 +79,7 @@ func Remove(h Interface, i int) interface{} {
func up(h Interface, j int) { func up(h Interface, j int) {
for { for {
i := (j - 1) / 2 // parent i := (j - 1) / 2 // parent
if i == j || h.Less(i, j) { if i == j || !h.Less(j, i) {
break break
} }
h.Swap(i, j) h.Swap(i, j)
...@@ -97,7 +97,7 @@ func down(h Interface, i, n int) { ...@@ -97,7 +97,7 @@ func down(h Interface, i, n int) {
if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) { if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) {
j = j2 // = 2*i + 2 // right child j = j2 // = 2*i + 2 // right child
} }
if h.Less(i, j) { if !h.Less(j, i) {
break break
} }
h.Swap(i, j) h.Swap(i, j)
......
...@@ -170,3 +170,16 @@ func TestRemove2(t *testing.T) { ...@@ -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)
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment