Skip to content

Commit

Permalink
Merge pull request #19 from bep/speedup-insert
Browse files Browse the repository at this point in the history
Speed up Insert
  • Loading branch information
armon authored Aug 5, 2022
2 parents 1a2de0c + 5172d42 commit 6ca3752
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
10 changes: 8 additions & 2 deletions radix.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,14 @@ func (n *node) isLeaf() bool {
}

func (n *node) addEdge(e edge) {
n.edges = append(n.edges, e)
n.edges.Sort()
num := len(n.edges)
idx := sort.Search(num, func(i int) bool {
return n.edges[i].label >= e.label
})

n.edges = append(n.edges, edge{})
copy(n.edges[idx+1:], n.edges[idx:])
n.edges[idx] = e
}

func (n *node) updateEdge(label byte, node *node) {
Expand Down
15 changes: 15 additions & 0 deletions radix_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"sort"
"strconv"
"testing"
)

Expand Down Expand Up @@ -357,3 +358,17 @@ func generateUUID() string {
buf[8:10],
buf[10:16])
}

func BenchmarkInsert(b *testing.B) {
r := New()
for i := 0; i < 10000; i++ {
r.Insert(fmt.Sprintf("init%d", i), true)
}
b.ResetTimer()
for n := 0; n < b.N; n++ {
_, updated := r.Insert(strconv.Itoa(n), true)
if updated {
b.Fatal("bad")
}
}
}

0 comments on commit 6ca3752

Please sign in to comment.