Skip to content
This repository was archived by the owner on Jul 31, 2023. It is now read-only.

Commit ad0b46e

Browse files
authored
Precompute encodeWithKeys buffer size to avoid resizes (#1269)
This is strictly an optimization. Right now we always undersize the buffer then later increase it. This changes the code to accurately size it the first time to ensure we never re-allocate. ``` name old time/op new time/op delta RecordReqCommand-6 2.26µs ± 5% 2.10µs ± 5% -7.39% (p=0.000 n=10+10) RecordViaStats-6 2.70µs ± 5% 2.53µs ± 4% -6.31% (p=0.000 n=10+10) name old alloc/op new alloc/op delta RecordReqCommand-6 426B ± 0% 384B ± 0% -9.86% (p=0.000 n=10+10) RecordViaStats-6 594B ± 0% 552B ± 0% -7.07% (p=0.000 n=10+10) name old allocs/op new allocs/op delta RecordReqCommand-6 25.0 ± 0% 17.0 ± 0% -32.00% (p=0.000 n=10+10) RecordViaStats-6 28.0 ± 0% 20.0 ± 0% -28.57% (p=0.000 n=10+10) ```
1 parent a55fb71 commit ad0b46e

1 file changed

Lines changed: 8 additions & 1 deletion

File tree

stats/view/collector.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,15 @@ func (c *collector) clearRows() {
5959
// encodeWithKeys encodes the map by using values
6060
// only associated with the keys provided.
6161
func encodeWithKeys(m *tag.Map, keys []tag.Key) []byte {
62+
// Compute the buffer length we will need ahead of time to avoid resizing later
63+
reqLen := 0
64+
for _, k := range keys {
65+
s, _ := m.Value(k)
66+
// We will store each key + its length
67+
reqLen += len(s) + 1
68+
}
6269
vb := &tagencoding.Values{
63-
Buffer: make([]byte, len(keys)),
70+
Buffer: make([]byte, reqLen),
6471
}
6572
for _, k := range keys {
6673
v, _ := m.Value(k)

0 commit comments

Comments
 (0)