Skip to content

Commit

Permalink
Improve the iterate seek to O(logN) (#25)
Browse files Browse the repository at this point in the history
* improve the iterate seek to O(logN)

* add benchmark
  • Loading branch information
nolouch authored and gconnell committed Aug 13, 2018
1 parent e89373f commit 4030bb1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
21 changes: 15 additions & 6 deletions btree.go
Original file line number Diff line number Diff line change
Expand Up @@ -500,13 +500,14 @@ const (
// thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
// "greaterThan" or "lessThan" queries.
func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) {
var ok bool
var ok, found bool
var index int
switch dir {
case ascend:
for i := 0; i < len(n.items); i++ {
if start != nil && n.items[i].Less(start) {
continue
}
if start != nil {
index, _ = n.items.find(start)
}
for i := index; i < len(n.items); i++ {
if len(n.children) > 0 {
if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
return hit, false
Expand All @@ -530,7 +531,15 @@ func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit b
}
}
case descend:
for i := len(n.items) - 1; i >= 0; i-- {
if start != nil {
index, found = n.items.find(start)
if !found {
index = index - 1
}
} else {
index = len(n.items) - 1
}
for i := index; i >= 0; i-- {
if start != nil && !n.items[i].Less(start) {
if !includeStart || hit || start.Less(n.items[i]) {
continue
Expand Down
15 changes: 15 additions & 0 deletions btree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,21 @@ func BenchmarkInsert(b *testing.B) {
}
}

func BenchmarkSeek(b *testing.B) {
b.StopTimer()
size := 100000
insertP := perm(size)
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
}
b.StartTimer()

for i := 0; i < b.N; i++ {
tr.AscendGreaterOrEqual(Int(i%size), func(i Item) bool { return false })
}
}

func BenchmarkDeleteInsert(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
Expand Down

0 comments on commit 4030bb1

Please sign in to comment.