Skip to content

Commit ee7af1e

Browse files
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 <david.mollitor@databricks.com>
1 parent e43f451 commit ee7af1e

1 file changed

Lines changed: 18 additions & 0 deletions

File tree

  • prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats

‎prometheus-metrics-exposition-textformats/src/main/java/io/prometheus/metrics/expositionformats/TextFormatUtil.java‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,24 @@ public static MetricSnapshots mergeDuplicates(MetricSnapshots metricSnapshots) {
4141
return metricSnapshots;
4242
}
4343

44+
// MetricSnapshots is sorted by prometheus name, so any duplicates are adjacent. Detect them in
45+
// a single allocation-free pass; when there are none (the common case) return the input as-is
46+
// rather than rebuilding it through a map, a list per group and a new MetricSnapshots.
47+
boolean hasDuplicates = false;
48+
for (int i = 1; i < metricSnapshots.size(); i++) {
49+
if (metricSnapshots
50+
.get(i)
51+
.getMetadata()
52+
.getPrometheusName()
53+
.equals(metricSnapshots.get(i - 1).getMetadata().getPrometheusName())) {
54+
hasDuplicates = true;
55+
break;
56+
}
57+
}
58+
if (!hasDuplicates) {
59+
return metricSnapshots;
60+
}
61+
4462
Map<String, List<MetricSnapshot>> grouped = new LinkedHashMap<>();
4563

4664
for (MetricSnapshot snapshot : metricSnapshots) {

0 commit comments

Comments
 (0)