From 2bd104c39bfbe14ea11168c701f83ba600747f07 Mon Sep 17 00:00:00 2001 From: jay23606 Date: Wed, 11 Nov 2026 00:36:08 -0500 Subject: [PATCH 1/2] Preallocate WKB output buffer in AsBinary using exact byte count --- CHANGELOG.md | 5 +- geom/perf_test.go | 2 + geom/type_bytes_in_wkb_internal_test.go | 54 +++++++++++++++++++++ geom/type_bytes_in_wkb_len_internal_test.go | 13 +++++ geom/type_geometry.go | 12 ++++- geom/type_geometry_collection.go | 12 ++++- geom/type_line_string.go | 8 ++- geom/type_multi_line_string.go | 12 ++++- geom/type_multi_point.go | 12 ++++- geom/type_multi_polygon.go | 12 ++++- geom/type_point.go | 8 ++- geom/type_polygon.go | 12 ++++- geom/wkb_marshal.go | 12 +++++ 13 files changed, 164 insertions(+), 10 deletions(-) create mode 100644 geom/type_bytes_in_wkb_internal_test.go create mode 100644 geom/type_bytes_in_wkb_len_internal_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 60dcbff4..d3143b8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,8 +13,9 @@ values directly to the output buffer using the `encoding/binary` append functions added in Go 1.19. `AsBinary` and `AppendWKB` make fewer heap allocations (previously, each coordinate of a `Point` or `MultiPoint` and each - WKB header field caused an allocation), and `MarshalTWKB` is around 20% to 30% - faster for geometries with 1,000 or more points. + WKB header field caused an allocation), and `AsBinary` now allocates its + output buffer once, at the exact size of the WKB. `MarshalTWKB` is around 20% + to 30% faster for geometries with 1,000 or more points. - Fix a panic in `UnmarshalTWKB` when parsing a TWKB whose element count (point count, ring point count, or ID list length) is far larger than the remaining diff --git a/geom/perf_test.go b/geom/perf_test.go index c9feb393..d9628bb3 100644 --- a/geom/perf_test.go +++ b/geom/perf_test.go @@ -34,6 +34,7 @@ func BenchmarkMarshalWKB(b *testing.B) { for _, sz := range []int{10, 100, 1000, 10000} { b.Run(fmt.Sprintf("n=%d", sz), func(b *testing.B) { poly := regularPolygon(geom.XY{}, 1.0, sz) + b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { poly.AsBinary() @@ -50,6 +51,7 @@ func BenchmarkMarshalWKB(b *testing.B) { pts[i] = geom.XY{X: rnd.Float64(), Y: rnd.Float64()}.AsPoint() } mp := geom.NewMultiPoint(pts) + b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { mp.AsBinary() diff --git a/geom/type_bytes_in_wkb_internal_test.go b/geom/type_bytes_in_wkb_internal_test.go new file mode 100644 index 00000000..cdff8b0d --- /dev/null +++ b/geom/type_bytes_in_wkb_internal_test.go @@ -0,0 +1,54 @@ +package geom + +import "testing" + +// wkbTestGeometries returns a geometry of each type, including empty and null +// edge cases. +func wkbTestGeometries() []Geometry { + seqXY := NewSequence([]float64{0, 0, 1, 0, 1, 1, 0, 0}, DimXY) + seqXYZM := NewSequence([]float64{0, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3, 4}, DimXYZM) + ring := NewLineString(seqXY) + poly := NewPolygon([]LineString{ring}) + polyZ := NewPolygon([]LineString{NewLineString(seqXYZM)}) + pt := NewPoint(Coordinates{XY: XY{1, 2}, Type: DimXYZ, Z: 3}) + emptyPt := NewEmptyPoint(DimXYM) + mp := NewMultiPoint([]Point{pt, emptyPt}) + mls := NewMultiLineString([]LineString{ring, NewLineString(seqXYZM)}) + mpoly := NewMultiPolygon([]Polygon{poly, polyZ}) + gc := NewGeometryCollection([]Geometry{ + pt.AsGeometry(), + ring.AsGeometry(), + poly.AsGeometry(), + mp.AsGeometry(), + mls.AsGeometry(), + mpoly.AsGeometry(), + NewGeometryCollection(nil).AsGeometry(), + }) + return []Geometry{ + pt.AsGeometry(), + emptyPt.AsGeometry(), + ring.AsGeometry(), + poly.AsGeometry(), + mp.AsGeometry(), + mls.AsGeometry(), + mpoly.AsGeometry(), + gc.AsGeometry(), + {}, + } +} + +// TestBytesInWKBMatchesAsBinary checks that AsBinary allocates its output +// buffer once, sized exactly to the WKB (so cap equals len and no growth +// happens during appending). +func TestBytesInWKBMatchesAsBinary(t *testing.T) { + for i, g := range wkbTestGeometries() { + b := g.AsBinary() + if cap(b) != len(b) { + t.Errorf("AsBinary buffer not sized exactly: geometry %d len=%d cap=%d", i, len(b), cap(b)) + } + allocs := testing.AllocsPerRun(10, func() { _ = g.AsBinary() }) + if allocs != 1 { + t.Errorf("AsBinary allocation count: geometry %d allocs=%v, want 1", i, allocs) + } + } +} diff --git a/geom/type_bytes_in_wkb_len_internal_test.go b/geom/type_bytes_in_wkb_len_internal_test.go new file mode 100644 index 00000000..5da4ddb1 --- /dev/null +++ b/geom/type_bytes_in_wkb_len_internal_test.go @@ -0,0 +1,13 @@ +package geom + +import "testing" + +// TestBytesInWKBLenMatchesAsBinary checks that bytesInWKB returns the same +// number as the len of the WKB produced by AsBinary. +func TestBytesInWKBLenMatchesAsBinary(t *testing.T) { + for i, g := range wkbTestGeometries() { + if got, want := len(g.AsBinary()), g.bytesInWKB(); got != want { + t.Errorf("bytesInWKB mismatch: geometry %d len(AsBinary)=%d bytesInWKB=%d", i, got, want) + } + } +} diff --git a/geom/type_geometry.go b/geom/type_geometry.go index 6d9a0e28..1590b7d8 100644 --- a/geom/type_geometry.go +++ b/geom/type_geometry.go @@ -17,6 +17,7 @@ type Geometry struct { MarshalJSON() ([]byte, error) AppendWKT(dst []byte) []byte AppendWKB(dst []byte) []byte + bytesInWKB() int IsEmpty() bool Envelope() Envelope Centroid() Point @@ -288,7 +289,16 @@ func (g Geometry) AppendWKT(dst []byte) []byte { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (g Geometry) AsBinary() []byte { - return g.AppendWKB(nil) + return g.AppendWKB(make([]byte, 0, g.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (g Geometry) bytesInWKB() int { + if g.impl == nil { + return GeometryCollection{}.bytesInWKB() + } + return g.impl.bytesInWKB() } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_geometry_collection.go b/geom/type_geometry_collection.go index ea06e737..035d3455 100644 --- a/geom/type_geometry_collection.go +++ b/geom/type_geometry_collection.go @@ -191,7 +191,17 @@ func (c *GeometryCollection) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (c GeometryCollection) AsBinary() []byte { - return c.AppendWKB(nil) + return c.AppendWKB(make([]byte, 0, c.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (c GeometryCollection) bytesInWKB() int { + n := wkbHeaderBytes + wkbCountBytes + for i := 0; i < c.NumGeometries(); i++ { + n += c.GeometryN(i).bytesInWKB() + } + return n } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_line_string.go b/geom/type_line_string.go index 6d219848..dfe6d1b9 100644 --- a/geom/type_line_string.go +++ b/geom/type_line_string.go @@ -250,7 +250,13 @@ func (s *LineString) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (s LineString) AsBinary() []byte { - return s.AppendWKB(nil) + return s.AppendWKB(make([]byte, 0, s.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (s LineString) bytesInWKB() int { + return wkbHeaderBytes + wkbSequenceBytes(s.seq) } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_multi_line_string.go b/geom/type_multi_line_string.go index afbba577..3aa07958 100644 --- a/geom/type_multi_line_string.go +++ b/geom/type_multi_line_string.go @@ -275,7 +275,17 @@ func (m *MultiLineString) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (m MultiLineString) AsBinary() []byte { - return m.AppendWKB(nil) + return m.AppendWKB(make([]byte, 0, m.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (m MultiLineString) bytesInWKB() int { + n := wkbHeaderBytes + wkbCountBytes + for _, ls := range m.lines { + n += ls.bytesInWKB() + } + return n } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_multi_point.go b/geom/type_multi_point.go index a83c6f34..73b02168 100644 --- a/geom/type_multi_point.go +++ b/geom/type_multi_point.go @@ -151,7 +151,17 @@ func (m *MultiPoint) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (m MultiPoint) AsBinary() []byte { - return m.AppendWKB(nil) + return m.AppendWKB(make([]byte, 0, m.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (m MultiPoint) bytesInWKB() int { + n := wkbHeaderBytes + wkbCountBytes + for _, pt := range m.points { + n += pt.bytesInWKB() + } + return n } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_multi_polygon.go b/geom/type_multi_polygon.go index c5cd93e6..91bac91d 100644 --- a/geom/type_multi_polygon.go +++ b/geom/type_multi_polygon.go @@ -279,7 +279,17 @@ func (m *MultiPolygon) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (m MultiPolygon) AsBinary() []byte { - return m.AppendWKB(nil) + return m.AppendWKB(make([]byte, 0, m.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (m MultiPolygon) bytesInWKB() int { + n := wkbHeaderBytes + wkbCountBytes + for i := 0; i < m.NumPolygons(); i++ { + n += m.PolygonN(i).bytesInWKB() + } + return n } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_point.go b/geom/type_point.go index 564f6903..996039f5 100644 --- a/geom/type_point.go +++ b/geom/type_point.go @@ -128,7 +128,13 @@ func (p *Point) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (p Point) AsBinary() []byte { - return p.AppendWKB(nil) + return p.AppendWKB(make([]byte, 0, p.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (p Point) bytesInWKB() int { + return wkbHeaderBytes + 8*p.coords.Type.Dimension() } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/type_polygon.go b/geom/type_polygon.go index 3805e199..20dd5903 100644 --- a/geom/type_polygon.go +++ b/geom/type_polygon.go @@ -282,7 +282,17 @@ func (p *Polygon) Scan(src any) error { // AsBinary returns the WKB (Well Known Text) representation of the geometry. func (p Polygon) AsBinary() []byte { - return p.AppendWKB(nil) + return p.AppendWKB(make([]byte, 0, p.bytesInWKB())) +} + +// bytesInWKB returns the number of bytes in the WKB representation of the +// geometry. +func (p Polygon) bytesInWKB() int { + n := wkbHeaderBytes + wkbCountBytes + for _, ring := range p.rings { + n += wkbSequenceBytes(ring.seq) + } + return n } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/wkb_marshal.go b/geom/wkb_marshal.go index 25530848..8b5d1cd4 100644 --- a/geom/wkb_marshal.go +++ b/geom/wkb_marshal.go @@ -25,6 +25,18 @@ func init() { } } +// wkbHeaderBytes is the size of the byte order and geometry type fields that +// prefix every WKB geometry. +const wkbHeaderBytes = 1 + 4 + +// wkbCountBytes is the size of a uint32 count field. +const wkbCountBytes = 4 + +// wkbSequenceBytes is the number of bytes written by writeSequence for seq. +func wkbSequenceBytes(seq Sequence) int { + return wkbCountBytes + 8*len(seq.floats) +} + type wkbMarshaler struct { buf []byte } From 991d2759193e22352303aee3670211a1b28e1bca Mon Sep 17 00:00:00 2001 From: jay23606 <4602056+jay23606@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:04:15 -0500 Subject: [PATCH 2/2] Address review feedback --- geom/marshal_unmarshal_test.go | 1 + geom/type_bytes_in_wkb_internal_test.go | 54 --------------------- geom/type_bytes_in_wkb_len_internal_test.go | 13 ----- geom/type_geometry_test.go | 3 +- geom/type_multi_point.go | 7 +-- geom/wkb_test.go | 1 + 6 files changed, 6 insertions(+), 73 deletions(-) delete mode 100644 geom/type_bytes_in_wkb_internal_test.go delete mode 100644 geom/type_bytes_in_wkb_len_internal_test.go diff --git a/geom/marshal_unmarshal_test.go b/geom/marshal_unmarshal_test.go index 8bb39519..855316d6 100644 --- a/geom/marshal_unmarshal_test.go +++ b/geom/marshal_unmarshal_test.go @@ -194,6 +194,7 @@ func TestMarshalUnmarshal(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { original := test.FromWKT(t, wkt) wkb := original.AsBinary() + test.Eq(t, cap(wkb), len(wkb)) reconstructed, err := geom.UnmarshalWKB(wkb) test.NoErr(t, err) reconstructedWKT := reconstructed.AsText() diff --git a/geom/type_bytes_in_wkb_internal_test.go b/geom/type_bytes_in_wkb_internal_test.go deleted file mode 100644 index cdff8b0d..00000000 --- a/geom/type_bytes_in_wkb_internal_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package geom - -import "testing" - -// wkbTestGeometries returns a geometry of each type, including empty and null -// edge cases. -func wkbTestGeometries() []Geometry { - seqXY := NewSequence([]float64{0, 0, 1, 0, 1, 1, 0, 0}, DimXY) - seqXYZM := NewSequence([]float64{0, 0, 1, 2, 3, 4, 0, 0, 1, 2, 3, 4}, DimXYZM) - ring := NewLineString(seqXY) - poly := NewPolygon([]LineString{ring}) - polyZ := NewPolygon([]LineString{NewLineString(seqXYZM)}) - pt := NewPoint(Coordinates{XY: XY{1, 2}, Type: DimXYZ, Z: 3}) - emptyPt := NewEmptyPoint(DimXYM) - mp := NewMultiPoint([]Point{pt, emptyPt}) - mls := NewMultiLineString([]LineString{ring, NewLineString(seqXYZM)}) - mpoly := NewMultiPolygon([]Polygon{poly, polyZ}) - gc := NewGeometryCollection([]Geometry{ - pt.AsGeometry(), - ring.AsGeometry(), - poly.AsGeometry(), - mp.AsGeometry(), - mls.AsGeometry(), - mpoly.AsGeometry(), - NewGeometryCollection(nil).AsGeometry(), - }) - return []Geometry{ - pt.AsGeometry(), - emptyPt.AsGeometry(), - ring.AsGeometry(), - poly.AsGeometry(), - mp.AsGeometry(), - mls.AsGeometry(), - mpoly.AsGeometry(), - gc.AsGeometry(), - {}, - } -} - -// TestBytesInWKBMatchesAsBinary checks that AsBinary allocates its output -// buffer once, sized exactly to the WKB (so cap equals len and no growth -// happens during appending). -func TestBytesInWKBMatchesAsBinary(t *testing.T) { - for i, g := range wkbTestGeometries() { - b := g.AsBinary() - if cap(b) != len(b) { - t.Errorf("AsBinary buffer not sized exactly: geometry %d len=%d cap=%d", i, len(b), cap(b)) - } - allocs := testing.AllocsPerRun(10, func() { _ = g.AsBinary() }) - if allocs != 1 { - t.Errorf("AsBinary allocation count: geometry %d allocs=%v, want 1", i, allocs) - } - } -} diff --git a/geom/type_bytes_in_wkb_len_internal_test.go b/geom/type_bytes_in_wkb_len_internal_test.go deleted file mode 100644 index 5da4ddb1..00000000 --- a/geom/type_bytes_in_wkb_len_internal_test.go +++ /dev/null @@ -1,13 +0,0 @@ -package geom - -import "testing" - -// TestBytesInWKBLenMatchesAsBinary checks that bytesInWKB returns the same -// number as the len of the WKB produced by AsBinary. -func TestBytesInWKBLenMatchesAsBinary(t *testing.T) { - for i, g := range wkbTestGeometries() { - if got, want := len(g.AsBinary()), g.bytesInWKB(); got != want { - t.Errorf("bytesInWKB mismatch: geometry %d len(AsBinary)=%d bytesInWKB=%d", i, got, want) - } - } -} diff --git a/geom/type_geometry_test.go b/geom/type_geometry_test.go index faf68ad4..21478a6d 100644 --- a/geom/type_geometry_test.go +++ b/geom/type_geometry_test.go @@ -35,7 +35,8 @@ func TestZeroGeometry(t *testing.T) { test.Eq(t, z.IsEmpty(), true) z = geom.Geometry{} - _ = z.AsBinary() // Doesn't crash + zWKB := z.AsBinary() // Doesn't crash + test.Eq(t, cap(zWKB), len(zWKB)) _, err = z.Value() test.NoErr(t, err) diff --git a/geom/type_multi_point.go b/geom/type_multi_point.go index 73b02168..a1176bf9 100644 --- a/geom/type_multi_point.go +++ b/geom/type_multi_point.go @@ -157,11 +157,8 @@ func (m MultiPoint) AsBinary() []byte { // bytesInWKB returns the number of bytes in the WKB representation of the // geometry. func (m MultiPoint) bytesInWKB() int { - n := wkbHeaderBytes + wkbCountBytes - for _, pt := range m.points { - n += pt.bytesInWKB() - } - return n + ptBytes := wkbHeaderBytes + 8*m.ctype.Dimension() + return wkbHeaderBytes + wkbCountBytes + len(m.points)*ptBytes } // AppendWKB appends the WKB (Well Known Text) representation of the geometry diff --git a/geom/wkb_test.go b/geom/wkb_test.go index f1ea4ac2..6585a7ae 100644 --- a/geom/wkb_test.go +++ b/geom/wkb_test.go @@ -566,6 +566,7 @@ func TestWKBMarshalValid(t *testing.T) { t.Run(strconv.Itoa(i), func(t *testing.T) { g := test.FromWKT(t, wkt) buf := g.AsBinary() + test.Eq(t, cap(buf), len(buf)) readBackGeom, err := geom.UnmarshalWKB(buf) test.NoErr(t, err) test.ExactEquals(t, readBackGeom, g)