Skip to content

Commit b504328

Browse files
authored
CellID.AllNeighbors: Allocate memory in one go (#213)
Pre-allocate memory to avoid triggering expansion, and enhance performance. - Before: ``` BenchmarkAllNeighbors/level12 3699290 322.9 ns/op 120 B/op 4 allocs/op BenchmarkAllNeighbors/level14 1699875 700.6 ns/op 504 B/op 6 allocs/op BenchmarkAllNeighbors/level16 594056 2091 ns/op 2040 B/op 8 allocs/op ``` - After: ``` BenchmarkAllNeighbors/level12 5084275 254.1 ns/op 64 B/op 1 allocs/op BenchmarkAllNeighbors/level14 2295961 510.6 ns/op 160 B/op 1 allocs/op BenchmarkAllNeighbors/level16 786132 1610 ns/op 576 B/op 1 allocs/op ```
1 parent 39b3d98 commit b504328

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

s2/cellid.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ func (ci CellID) AllNeighbors(level int) []CellID {
276276
return nil
277277
}
278278

279-
var neighbors []CellID
279+
var neighbors = make([]CellID, 0, (4<<(level-ci.Level()))+4)
280280

281281
face, i, j, _ := ci.faceIJOrientation()
282282

s2/cellid_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package s2
1616

1717
import (
18+
"fmt"
1819
"math"
1920
"reflect"
2021
"testing"
@@ -1046,6 +1047,25 @@ func TestCellIDCenterFaceSiTi(t *testing.T) {
10461047
}
10471048
}
10481049

1050+
func BenchmarkAllNeighbors(b *testing.B) {
1051+
level := 12
1052+
ll := LatLngFromDegrees(10.100001, 10.100002)
1053+
cellID := CellIDFromLatLng(ll).Parent(level)
1054+
1055+
cases := []int{level, level + 2, level + 4}
1056+
1057+
for _, n := range cases {
1058+
b.Run(fmt.Sprintf("level%d", n), func(b *testing.B) {
1059+
b.ResetTimer()
1060+
b.ReportAllocs()
1061+
1062+
for i := 0; i < b.N; i++ {
1063+
cellID.AllNeighbors(n)
1064+
}
1065+
})
1066+
}
1067+
}
1068+
10491069
// TODO(roberts): Remaining tests to convert.
10501070
// Coverage
10511071
// TraversalOrder

0 commit comments

Comments
 (0)