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

Avoid one memory allocation in LabelSet construction #318

Merged
merged 1 commit into from
Nov 14, 2019
Merged
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
30 changes: 16 additions & 14 deletions sdk/metric/sdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ type (
// repeatedly.
labels struct {
meter *SDK
sorted []core.KeyValue
sorted sortedLabels
encoded string
}

Expand Down Expand Up @@ -245,39 +245,41 @@ func (m *SDK) Labels(kvs ...core.KeyValue) api.LabelSet {
return &m.empty
}

ls := &labels{
meter: m,
sorted: kvs,
}

// Sort and de-duplicate.
sorted := sortedLabels(kvs)
sort.Stable(&sorted)
sort.Stable(&ls.sorted)
oi := 1
for i := 1; i < len(sorted); i++ {
if sorted[i-1].Key == sorted[i].Key {
sorted[oi-1] = sorted[i]
for i := 1; i < len(ls.sorted); i++ {
if ls.sorted[i-1].Key == ls.sorted[i].Key {
ls.sorted[oi-1] = ls.sorted[i]
continue
}
sorted[oi] = sorted[i]
ls.sorted[oi] = ls.sorted[i]
oi++
}
sorted = sorted[0:oi]
ls.sorted = ls.sorted[0:oi]

// Serialize.
buf := m.pool.Get().(*bytes.Buffer)
defer m.pool.Put(buf)
buf.Reset()
_, _ = buf.WriteRune('|')
delimiter := '#'
for _, kv := range sorted {
for _, kv := range ls.sorted {
_, _ = buf.WriteRune(delimiter)
_, _ = buf.WriteString(string(kv.Key))
_, _ = buf.WriteRune(':')
_, _ = buf.WriteString(kv.Value.Emit())
delimiter = ','
}

return &labels{
meter: m,
sorted: sorted,
encoded: buf.String(),
}
ls.encoded = buf.String()

return ls
}

// labsFor sanitizes the input LabelSet. The input will be rejected
Expand Down