From 0009364776b2bc9e8e5efa60cdc3263030666bb2 Mon Sep 17 00:00:00 2001 From: John Howard Date: Tue, 14 Sep 2021 10:26:21 -0700 Subject: [PATCH] Precompute encodeWithKeys buffer size to avoid resizes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) ``` --- stats/view/collector.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/stats/view/collector.go b/stats/view/collector.go index ac22c93a2..ffdbb7089 100644 --- a/stats/view/collector.go +++ b/stats/view/collector.go @@ -59,8 +59,15 @@ func (c *collector) clearRows() { // encodeWithKeys encodes the map by using values // only associated with the keys provided. func encodeWithKeys(m *tag.Map, keys []tag.Key) []byte { + // Compute the buffer length we will need ahead of time to avoid resizing latter + reqLen := 0 + for _, k := range keys { + s, _ := m.Value(k) + // We will store each key + its length + reqLen += len(s) + 1 + } vb := &tagencoding.Values{ - Buffer: make([]byte, len(keys)), + Buffer: make([]byte, reqLen), } for _, k := range keys { v, _ := m.Value(k)