Cache the repeated bucket metric name

perfloop/prometheus · ALLOCATION HOT LOOP

https://perfloop.ai/t/oss/case_9n8a709kej

Verdict

VERIFIED · settled 2026-09-16 · merged as prometheus/prometheus#19717

What happened: The paired measurements met the required improvement.

Hypothesis

The target's inner bucket loop concatenates `appOpts.MetricFamilyName+bucketStr` at line 333 for every finite bound and again at line 345 for +Inf; `addLabels` consumes that name to form the emitted label set. `FromMetrics` selects this function when `ConvertHistogramsToNHCB` is false, so this cadence is once per OTLP explicit-histogram data point and then once per emitted finite bucket. The focused compiler check `go test -run '^$' -gcflags='-m=2' ./storage/remote/otlptranslator/prometheusremotewrite` reported that the concatenations at lines 284, 295, 333, and 345 escape to the heap. Thus the bucket expression alone creates B+1 escaping name strings per data point today, while one cached bucket name would create one; the removed delta is B escaping concatenations per one-point histogram (or sum(B)+D-1 across D points). This establishes allocation shape, not measured end-to-end CPU or GC impact. The narrow behavior check `go test ./storage/remote/otlptranslator/prometheusremotewrite -run '^(TestPrometheusConverter_AddHistogramDataPoints|TestAddHistogramDataPoints_ExemplarLeakAcrossDataPoints)$' -count=1` passed on the baseline. Proof target: add a focused explicit-histogram benchmark varying finite-bound count and data-point count, then compare allocs/op, bytes/op, CPU, and GC against the cached-name version; it must show the predicted bucket-name allocation drop while preserving the exact emitted samples and exemplar routing.

Change to test: Build the invariant `<metric-family>_bucket` string once before the data-point loop and reuse it for finite and +Inf bucket labels; cache the count and conditionally-needed sum names similarly only where doing so cannot introduce work for absent sums.

Where it lives

perfloop/prometheus · storage/remote/write_otlp_handler.go

Evidence

FromMetrics explicit histogram, 64 points and 64 finite bounds · 10 sample pairs

metric baseline candidate paired median change confidence range required result
ns/op 1016122 830018 −18.3% (−185761) −201466 to −154357 < −50806 PASSED
B/op 427372 291234 −31.9% (−136138) −136142 to −136135 < −21369 PASSED
allocs/op 12242 7957 −35% (−4285) −4285 to −4285 < −612.1 PASSED

Checks: 4 of 4 passed. Verification: no defect found.

Timeline