prometheus / common

Go libraries shared across Prometheus components and libraries.
Apache License 2.0
262 stars 316 forks source link

labelset: optimise String() function #590

Closed bboreham closed 7 months ago

bboreham commented 7 months ago

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.

goos: linux
goarch: amd64
pkg: github.com/prometheus/common/model
cpu: Intel(R) Core(TM) i7-14700K
                       │  before.txt   │             after.txt              │
                       │    sec/op     │   sec/op     vs base               │
LabelSetStringMethod-4   1243.0n ± 13%   286.8n ± 5%  -76.93% (p=0.002 n=6)

                       │ before.txt  │             after.txt             │
                       │    B/op     │    B/op     vs base               │
LabelSetStringMethod-4   608.00 ± 0%   80.00 ± 0%  -86.84% (p=0.002 n=6)

                       │ before.txt  │             after.txt             │
                       │  allocs/op  │ allocs/op   vs base               │
LabelSetStringMethod-4   21.000 ± 0%   1.000 ± 0%  -95.24% (p=0.002 n=6)