Skip to content

Commit

Permalink
prune: speed up using 1<<N instead of math.Pow(2, N)
Browse files Browse the repository at this point in the history
This change fixes the use of expensive code that used
math.Pow(float(2), N) but really that's expensive code
that could be simplified by using left bitshifts.

The improvements in speed show in benchmarks:

```shell
$ benchstat before.txt after.txt
name    old time/op    new time/op    delta
Pow2-8     322ns ± 2%     114ns ± 1%  -64.69%  (p=0.000 n=9+8)

name    old alloc/op   new alloc/op   delta
Pow2-8     40.0B ± 0%     40.0B ± 0%     ~     (all equal)

name    old allocs/op  new allocs/op  delta
Pow2-8      5.00 ± 0%      5.00 ± 0%     ~     (all equal)
```

Fixes #72
  • Loading branch information
odeke-em committed Oct 17, 2022
1 parent 230d27f commit 701097c
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion subrootpaths.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ func prune(idxStart uint, idxEnd uint, maxWidth uint) [][]int {
rightTraversed := false

for i := treeDepth - 1; i >= 0 && capturedSpan < idxEnd; i-- {
nodeSpan := uint(math.Pow(float64(2), float64(treeDepth-i)))
// nodeSpan is 2**(treeDepth-i) == 1<<(treeDepth-i)
// Please see: https://github.com/celestiaorg/nmt/issues/72
nodeSpan := 1 << (treeDepth - i)
if pathStart[i] == 0 {
// if nodespan is less than end index, continue traversing upwards
lastNode := nodeSpan + idxStart - 1
Expand Down

0 comments on commit 701097c

Please sign in to comment.