From ee7af1eda7e11b33339f4222e2ad3f2f8448681e Mon Sep 17 00:00:00 2001 From: David Mollitor Date: Tue, 1 Sep 2026 19:06:45 +0000 Subject: [PATCH] perf: skip snapshot rebuild in mergeDuplicates when names are unique MetricSnapshots is always sorted by prometheus name, so duplicate names are adjacent. Detect duplicates in a single allocation-free pass and, when there are none (the common case), return the input unchanged instead of rebuilding it through a LinkedHashMap, an ArrayList per group, a MetricSnapshots.Builder and a freshly sorted MetricSnapshots. The merge path for actual duplicates is unchanged. Output is byte-identical (verified by the existing exposition-format tests, including DuplicateNamesExpositionTest). Signed-off-by: David Mollitor --- .../expositionformats/TextFormatUtil.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java b/prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java index 8cfed2b29..9ca373e9f 100644 --- a/prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java +++ b/prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java @@ -41,6 +41,24 @@ public static MetricSnapshots mergeDuplicates(MetricSnapshots metricSnapshots) { return metricSnapshots; } + // MetricSnapshots is sorted by prometheus name, so any duplicates are adjacent. Detect them in + // a single allocation-free pass; when there are none (the common case) return the input as-is + // rather than rebuilding it through a map, a list per group and a new MetricSnapshots. + boolean hasDuplicates = false; + for (int i = 1; i < metricSnapshots.size(); i++) { + if (metricSnapshots + .get(i) + .getMetadata() + .getPrometheusName() + .equals(metricSnapshots.get(i - 1).getMetadata().getPrometheusName())) { + hasDuplicates = true; + break; + } + } + if (!hasDuplicates) { + return metricSnapshots; + } + Map> grouped = new LinkedHashMap<>(); for (MetricSnapshot snapshot : metricSnapshots) {