Skip to content

Commit

Permalink
labelset: optimise String() function (#590)
Browse files Browse the repository at this point in the history
Build the output in a `bytes.Buffer` to avoid creating small strings
which are passed to `Join`.

Use stack arrays to avoid allocations for small
buffers, and `AppendQuote`/`AvailableBuffer` avoids
allocating and copying in the case that buffer
space is sufficient.

Signed-off-by: Bryan Boreham <bjboreham@gmail.com>
  • Loading branch information
bboreham committed Feb 29, 2024
1 parent e8be06d commit 36d0bf9
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions model/labelset.go
Expand Up @@ -14,10 +14,12 @@
package model

import (
"bytes"
"encoding/json"
"fmt"
"slices"
"sort"
"strings"
"strconv"
)

// A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet
Expand Down Expand Up @@ -129,17 +131,27 @@ func (l LabelSet) Merge(other LabelSet) LabelSet {
return result
}

// String will look like `{foo="bar", more="less"}`. Names are sorted alphabetically.
func (l LabelSet) String() string {
labelNames := make([]string, 0, len(l))
var lna [32]LabelName // On stack to avoid memory allocation for sorting names.
labelNames := lna[:0]
for name := range l {
labelNames = append(labelNames, string(name))
labelNames = append(labelNames, name)
}
sort.Strings(labelNames)
lstrs := make([]string, 0, len(l))
for _, name := range labelNames {
lstrs = append(lstrs, fmt.Sprintf("%s=%q", name, l[LabelName(name)]))
slices.Sort(labelNames)
var bytea [1024]byte // On stack to avoid memory allocation while building the output.
b := bytes.NewBuffer(bytea[:0])
b.WriteByte('{')
for i, name := range labelNames {
if i > 0 {
b.WriteString(", ")
}
b.WriteString(string(name))
b.WriteByte('=')
b.Write(strconv.AppendQuote(b.AvailableBuffer(), string(l[name])))
}
return fmt.Sprintf("{%s}", strings.Join(lstrs, ", "))
b.WriteByte('}')
return b.String()
}

// Fingerprint returns the LabelSet's fingerprint.
Expand Down

0 comments on commit 36d0bf9

Please sign in to comment.