diff --git a/model/labelset.go b/model/labelset.go index 6eda08a7..ca855a0c 100644 --- a/model/labelset.go +++ b/model/labelset.go @@ -130,12 +130,15 @@ func (l LabelSet) Merge(other LabelSet) LabelSet { } func (l LabelSet) String() string { + labelNames := make([]string, 0, len(l)) + for name := range l { + labelNames = append(labelNames, string(name)) + } + sort.Strings(labelNames) lstrs := make([]string, 0, len(l)) - for l, v := range l { - lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v)) + for _, name := range labelNames { + lstrs = append(lstrs, fmt.Sprintf("%s=%q", name, l[LabelName(name)])) } - - sort.Strings(lstrs) return fmt.Sprintf("{%s}", strings.Join(lstrs, ", ")) } diff --git a/model/labelset_test.go b/model/labelset_test.go index c008816a..3f8824d6 100644 --- a/model/labelset_test.go +++ b/model/labelset_test.go @@ -27,7 +27,10 @@ func TestUnmarshalJSONLabelSet(t *testing.T) { labelSetJSON := `{ "labelSet": { "monitor": "codelab", - "foo": "bar" + "foo": "bar", + "foo2": "bar", + "abc": "prometheus", + "foo11": "bar11" } }` var c testConfig @@ -38,7 +41,7 @@ func TestUnmarshalJSONLabelSet(t *testing.T) { labelSetString := c.LabelSet.String() - expected := `{foo="bar", monitor="codelab"}` + expected := `{abc="prometheus", foo="bar", foo11="bar11", foo2="bar", monitor="codelab"}` if expected != labelSetString { t.Errorf("expected %s but got %s", expected, labelSetString) @@ -117,3 +120,23 @@ func TestLabelSetMerge(t *testing.T) { } } } + +// Benchmark Results for LabelSet's String() method +// --------------------------------------------------------------------------------------------------------- +// goos: linux +// goarch: amd64 +// pkg: github.com/prometheus/common/model +// cpu: 11th Gen Intel(R) Core(TM) i5-1145G7 @ 2.60GHz +// BenchmarkLabelSetStringMethod-8 732376 1532 ns/op + +func BenchmarkLabelSetStringMethod(b *testing.B) { + ls := make(LabelSet) + ls["monitor"] = "codelab" + ls["foo2"] = "bar" + ls["foo"] = "bar" + ls["abc"] = "prometheus" + ls["foo11"] = "bar11" + for i := 0; i < b.N; i++ { + _ = ls.String() + } +}