Skip to content

Commit

Permalink
More better ParseMetric performance!
Browse files Browse the repository at this point in the history
Turns out `strings.Builder` is actually pretty efficient! That along
with not calling `New()` and instead just calling `make(Labels)`
directly the ns/op time is cut in half for `ParseMetric`.
  • Loading branch information
sapslaj committed Jan 5, 2023
1 parent 0776c74 commit 9521369
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
20 changes: 13 additions & 7 deletions lokiclient/labels/labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"sort"
"strconv"
"strings"

"github.com/cespare/xxhash/v2"
"github.com/prometheus/common/model"
Expand Down Expand Up @@ -448,8 +449,9 @@ func (ls Labels) ReleaseStrings(release func(string)) {
func ParseMetric(s string) (result Labels, err error) {
var parsingKey bool
var parsingValue bool
result = New()
l := Label{}
result = make(Labels, 0)
var name strings.Builder
var value strings.Builder
for pos := 0; pos < len(s); pos++ {
b := s[pos]
if !parsingKey && !parsingValue {
Expand Down Expand Up @@ -478,24 +480,28 @@ func ParseMetric(s string) (result Labels, err error) {
if b == ' ' {
continue
}
l.Name += string(b)
name.WriteByte(b)
}
if parsingValue {
if b == '"' {
parsingValue = false
result = append(result, l)
l = Label{}
result = append(result, Label{
Name: name.String(),
Value: value.String(),
})
name.Reset()
value.Reset()
continue
}
if b == '\\' {
peek := s[pos+1]
if peek == '"' {
l.Value += "\""
value.WriteRune('"')
pos += 1
continue
}
}
l.Value += string(b)
value.WriteByte(b)
}
}
return
Expand Down
9 changes: 9 additions & 0 deletions lokiclient/labels/labels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -788,3 +788,12 @@ func TestParseMetric(t *testing.T) {
}
}
}

func BenchmarkParseMetric(b *testing.B) {
s := "{foo=\"bar\", bar=\"baz\"}"
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ParseMetric(s)
}
}

0 comments on commit 9521369

Please sign in to comment.