Skip to content

Commit 1e8e785

Browse files
committed
Remove allocs from WriteFloat32/WriteFloat64
The use of strconv.FormatFloat causes a string allocation, by setting aside a reusable buffer and using strconv.AppendFloat this can be avoided. Before: BenchmarkRespond-4 300 5392189 ns/op 618936 B/op 20010 allocs/op After: BenchmarkRespond-4 300 4713746 ns/op 139744 B/op 10 allocs/op This benchmark is using a custom encoder that calls WriteFloat64 20k times, which is the bulk of the work.
1 parent 002b5ae commit 1e8e785

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

feature_stream.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ type Stream struct {
1414
Error error
1515
indention int
1616
Attachment interface{} // open for customized encoder
17+
floatBuf []byte
1718
}
1819

1920
// NewStream create new stream instance.
@@ -28,6 +29,7 @@ func NewStream(cfg API, out io.Writer, bufSize int) *Stream {
2829
n: 0,
2930
Error: nil,
3031
indention: 0,
32+
floatBuf: make([]byte, 0, 32),
3133
}
3234
}
3335

feature_stream_float.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ func (stream *Stream) WriteFloat32(val float32) {
2121
fmt = 'e'
2222
}
2323
}
24-
stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 32))
24+
stream.floatBuf = strconv.AppendFloat(stream.floatBuf, float64(val), fmt, -1, 32)
25+
stream.Write(stream.floatBuf)
26+
stream.floatBuf = stream.floatBuf[:0]
2527
}
2628

2729
// WriteFloat32Lossy write float32 to stream with ONLY 6 digits precision although much much faster
@@ -63,7 +65,9 @@ func (stream *Stream) WriteFloat64(val float64) {
6365
fmt = 'e'
6466
}
6567
}
66-
stream.WriteRaw(strconv.FormatFloat(float64(val), fmt, -1, 64))
68+
stream.floatBuf = strconv.AppendFloat(stream.floatBuf, float64(val), fmt, -1, 64)
69+
stream.Write(stream.floatBuf)
70+
stream.floatBuf = stream.floatBuf[:0]
6771
}
6872

6973
// WriteFloat64Lossy write float64 to stream with ONLY 6 digits precision although much much faster

0 commit comments

Comments
 (0)