From 6f666c7bd27cb1561c6598ba0fe732a8edf7b512 Mon Sep 17 00:00:00 2001 From: john-doy <140866423+john-doy@users.noreply.github.com> Date: Mon, 27 Nov 2023 23:06:52 +0800 Subject: [PATCH 1/2] optimize memory usage Signed-off-by: ethanvc --- prometheus/internal/metric.go | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/prometheus/internal/metric.go b/prometheus/internal/metric.go index 6515c1148..f45780d03 100644 --- a/prometheus/internal/metric.go +++ b/prometheus/internal/metric.go @@ -83,19 +83,16 @@ func (s MetricSorter) Less(i, j int) bool { // MetricFamilies pruned and the remaining MetricFamilies sorted by name within // the slice, with the contained Metrics sorted within each MetricFamily. func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily { + result := make([]*dto.MetricFamily, 0, len(metricFamiliesByName)) for _, mf := range metricFamiliesByName { - sort.Sort(MetricSorter(mf.Metric)) - } - names := make([]string, 0, len(metricFamiliesByName)) - for name, mf := range metricFamiliesByName { - if len(mf.Metric) > 0 { - names = append(names, name) + if len(mf.Metric) == 0 { + continue } + sort.Sort(MetricSorter(mf.Metric)) + result = append(result, mf) } - sort.Strings(names) - result := make([]*dto.MetricFamily, 0, len(names)) - for _, name := range names { - result = append(result, metricFamiliesByName[name]) - } + sort.Slice(result, func(i, j int) bool { + return *result[i].Name < *result[j].Name + }) return result } From 15e70e5e630c17f014db09c513160a62eef711c6 Mon Sep 17 00:00:00 2001 From: ethanvc Date: Fri, 22 Dec 2023 22:33:59 +0800 Subject: [PATCH 2/2] make it more safer --- prometheus/internal/metric.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/prometheus/internal/metric.go b/prometheus/internal/metric.go index f45780d03..4491cccdf 100644 --- a/prometheus/internal/metric.go +++ b/prometheus/internal/metric.go @@ -92,7 +92,7 @@ func NormalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) result = append(result, mf) } sort.Slice(result, func(i, j int) bool { - return *result[i].Name < *result[j].Name + return result[i].GetName() < result[j].GetName() }) return result }