Skip to content

Commit 64cb148

Browse files
authored
regularPointsForFrame: Allocate memory in one go (#215)
- Before `BenchmarkPointRegularPoints-12 1476942 810.5 ns/op 360 B/op 4 allocs/op` - After `BenchmarkPointRegularPoints-12 2055764 548.6 ns/op 192 B/op 1 allocs/op`
1 parent ebe3c72 commit 64cb148

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

s2/point.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,12 +160,12 @@ func regularPointsForFrame(frame matrix3x3, radius s1.Angle, numVertices int) []
160160
z := math.Cos(radius.Radians())
161161
r := math.Sin(radius.Radians())
162162
radianStep := 2 * math.Pi / float64(numVertices)
163-
var vertices []Point
163+
var vertices = make([]Point, numVertices)
164164

165-
for i := 0; i < numVertices; i++ {
165+
for i := range vertices {
166166
angle := float64(i) * radianStep
167167
p := Point{r3.Vector{X: r * math.Cos(angle), Y: r * math.Sin(angle), Z: z}}
168-
vertices = append(vertices, Point{fromFrame(frame, p).Normalize()})
168+
vertices[i] = Point{fromFrame(frame, p).Normalize()}
169169
}
170170

171171
return vertices

s2/point_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,3 +458,13 @@ func TestPointEnsureNormalizable(t *testing.T) {
458458
}
459459
}
460460
}
461+
462+
func BenchmarkPointRegularPoints(b *testing.B) {
463+
center := PointFromLatLng(LatLngFromDegrees(80, 135))
464+
radius := s1.Degree * 20
465+
466+
b.ReportAllocs()
467+
for i := 0; i < b.N; i++ {
468+
regularPoints(center, radius, 8)
469+
}
470+
}

0 commit comments

Comments
 (0)