Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix excessive allocation in the resource metrics #1964

Merged
merged 6 commits into from
Dec 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 32 additions & 8 deletions metrics/resource_view.go
Original file line number Diff line number Diff line change
Expand Up @@ -315,21 +315,45 @@ func resourceToKey(r *resource.Resource) string {
if r == nil {
return ""
}

// If there are no labels, we have just the Type.
if len(r.Labels) == 0 {
return r.Type
}

var s strings.Builder
writeKV := func(key, value string) { // This lambda doesn't force an allocation.
// We use byte values 1 and 2 to avoid colliding with valid resource labels
// and to make unpacking easy
s.WriteByte('\x01')
s.WriteString(key)
s.WriteByte('\x02')
s.WriteString(value)
}

// If there's only one label, we can skip building and sorting a slice of keys.
if len(r.Labels) == 1 {
for k, v := range r.Labels {
// We know this only executes once.
s.Grow(len(r.Type) + len(k) + len(v) + 2)
s.WriteString(r.Type)
writeKV(k, v)
return s.String()
}
}

l := len(r.Type)
kvs := make([]string, 0, len(r.Labels))
keys := make([]string, 0, len(r.Labels))
for k, v := range r.Labels {
l += len(k) + len(v) + 2
// We use byte values 1 and 2 to avoid colliding with valid resource labels
// and to make unpacking easy
kvs = append(kvs, fmt.Sprintf("\x01%s\x02%s", k, v))
keys = append(keys, k)
}
s.Grow(l)
s.WriteString(r.Type)

sort.Strings(kvs) // Go maps are unsorted, so sort by key to produce stable output.
for _, kv := range kvs {
s.WriteString(kv)
s.WriteString(r.Type)
sort.Strings(keys) // Go maps are unsorted, so sort by key to produce stable output.
for _, key := range keys {
writeKV(key, r.Labels[key])
}

return s.String()
Expand Down
16 changes: 16 additions & 0 deletions metrics/resource_view_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,22 @@ func TestResourceAsString(t *testing.T) {
}
}

func BenchmarkResourceToKey(b *testing.B) {
for _, count := range []int{0, 1, 5, 10} {
labels := make(map[string]string, count)
for i := 0; i < count; i++ {
labels[fmt.Sprint("key", i)] = fmt.Sprint("value", i)
}
r := &resource.Resource{Type: "foobar", Labels: labels}

b.Run(fmt.Sprintf("%d-labels", count), func(b *testing.B) {
for i := 0; i < b.N; i++ {
resourceToKey(r)
}
})
}
}

type metricExtract struct {
Name string
Labels map[string]string
Expand Down