Preallocate Labels in labels.Builder (#10749)

This tries to avoid re-allocations of labels slice since we know possible max size

Signed-off-by: Łukasz Mierzwa <l.mierzwa@gmail.com>
This commit is contained in:
Łukasz Mierzwa 2022-05-25 15:22:47 +01:00 committed by GitHub
parent d3cb39044e
commit 08262454a3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 19 deletions

View File

@ -349,7 +349,7 @@ func FromStrings(ss ...string) Labels {
if len(ss)%2 != 0 {
panic("invalid number of strings")
}
var res Labels
res := make(Labels, 0, len(ss)/2)
for i := 0; i < len(ss); i += 2 {
res = append(res, Label{Name: ss[i], Value: ss[i+1]})
}
@ -452,7 +452,7 @@ func (b *Builder) Labels() Labels {
// In the general case, labels are removed, modified or moved
// rather than added.
res := make(Labels, 0, len(b.base))
res := make(Labels, 0, len(b.base)+len(b.add))
Outer:
for _, l := range b.base {
for _, n := range b.del {

View File

@ -16,6 +16,7 @@ package promql
import (
"context"
"errors"
"fmt"
"os"
"sort"
"testing"
@ -680,7 +681,6 @@ load 10s
Result: Matrix{
Series{
Points: []Point{{V: 1, T: 0}, {V: 1, T: 1000}, {V: 1, T: 2000}},
Metric: labels.FromStrings(),
},
},
Start: time.Unix(0, 0),
@ -717,24 +717,26 @@ load 10s
},
}
for _, c := range cases {
var err error
var qry Query
if c.Interval == 0 {
qry, err = test.QueryEngine().NewInstantQuery(test.Queryable(), nil, c.Query, c.Start)
} else {
qry, err = test.QueryEngine().NewRangeQuery(test.Queryable(), nil, c.Query, c.Start, c.End, c.Interval)
}
require.NoError(t, err)
for i, c := range cases {
t.Run(fmt.Sprintf("%d query=%s", i, c.Query), func(t *testing.T) {
var err error
var qry Query
if c.Interval == 0 {
qry, err = test.QueryEngine().NewInstantQuery(test.Queryable(), nil, c.Query, c.Start)
} else {
qry, err = test.QueryEngine().NewRangeQuery(test.Queryable(), nil, c.Query, c.Start, c.End, c.Interval)
}
require.NoError(t, err)
res := qry.Exec(test.Context())
if c.ShouldError {
require.Error(t, res.Err, "expected error for the query %q", c.Query)
continue
}
res := qry.Exec(test.Context())
if c.ShouldError {
require.Error(t, res.Err, "expected error for the query %q", c.Query)
return
}
require.NoError(t, res.Err)
require.Equal(t, c.Result, res.Value, "query %q failed", c.Query)
require.NoError(t, res.Err)
require.Equal(t, c.Result, res.Value, "query %q failed", c.Query)
})
}
}