Skip to content

Commit 4223c58

Browse files
nes1983dsymonds
authored andcommitted
s2: Optimise readFloat64 to speed up Rect decoding.
This speeds up this path by removing allocations. name old time/op new time/op delta RectDecode-12 491ns ± 4% 275ns ± 4% -44.07% (p=0.000 n=9+10) name old alloc/op new alloc/op delta RectDecode-12 112B ± 0% 56B ± 0% -50.00% (p=0.000 n=10+10) name old allocs/op new allocs/op delta RectDecode-12 9.00 ± 0% 2.00 ± 0% -77.78% (p=0.000 n=10+10) name old speed new speed delta RectDecode-12 66.8MB/s ± 5% 120.2MB/s ± 4% +79.86% (p=0.000 n=10+10) Signed-off-by: David Symonds <dsymonds@golang.org>
1 parent 0e6f757 commit 4223c58

File tree

1 file changed

+15
-28
lines changed

1 file changed

+15
-28
lines changed

s2/encode.go

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package s2
1717
import (
1818
"encoding/binary"
1919
"io"
20+
"math"
2021
)
2122

2223
const (
@@ -145,6 +146,15 @@ func asByteReader(r io.Reader) byteReader {
145146
type decoder struct {
146147
r byteReader // the real reader passed to Decode
147148
err error
149+
buf []byte
150+
}
151+
152+
// Get a buffer of size 8, to avoid allocating over and over.
153+
func (d *decoder) buffer() []byte {
154+
if d.buf == nil {
155+
d.buf = make([]byte, 8)
156+
}
157+
return d.buf
148158
}
149159

150160
func (d *decoder) readBool() (x bool) {
@@ -164,22 +174,6 @@ func (d *decoder) readInt8() (x int8) {
164174
return
165175
}
166176

167-
func (d *decoder) readInt16() (x int16) {
168-
if d.err != nil {
169-
return
170-
}
171-
d.err = binary.Read(d.r, binary.LittleEndian, &x)
172-
return
173-
}
174-
175-
func (d *decoder) readInt32() (x int32) {
176-
if d.err != nil {
177-
return
178-
}
179-
d.err = binary.Read(d.r, binary.LittleEndian, &x)
180-
return
181-
}
182-
183177
func (d *decoder) readInt64() (x int64) {
184178
if d.err != nil {
185179
return
@@ -212,20 +206,13 @@ func (d *decoder) readUint64() (x uint64) {
212206
return
213207
}
214208

215-
func (d *decoder) readFloat32() (x float32) {
209+
func (d *decoder) readFloat64() float64 {
216210
if d.err != nil {
217-
return
211+
return 0
218212
}
219-
d.err = binary.Read(d.r, binary.LittleEndian, &x)
220-
return
221-
}
222-
223-
func (d *decoder) readFloat64() (x float64) {
224-
if d.err != nil {
225-
return
226-
}
227-
d.err = binary.Read(d.r, binary.LittleEndian, &x)
228-
return
213+
buf := d.buffer()
214+
_, d.err = io.ReadFull(d.r, buf)
215+
return math.Float64frombits(binary.LittleEndian.Uint64(buf))
229216
}
230217

231218
func (d *decoder) readUvarint() (x uint64) {

0 commit comments

Comments
 (0)