app/vmselect/promql: remove memory allocations from sortMetricTags()

This commit is contained in:
Aliaksandr Valialkin 2023-01-09 22:22:12 -08:00
parent 8050f5a18c
commit dd92e2050f
No known key found for this signature in database
GPG key ID: A72BEC6CD3D0DED1

View file

@ -321,26 +321,16 @@ func marshalMetricTagsFast(dst []byte, tags []storage.Tag) []byte {
func marshalMetricNameSorted(dst []byte, mn *storage.MetricName) []byte {
// Do not marshal AccountID and ProjectID, since they are unused.
dst = marshalBytesFast(dst, mn.MetricGroup)
sortMetricTags(mn.Tags)
sortMetricTags(mn)
dst = marshalMetricTagsFast(dst, mn.Tags)
return dst
}
func marshalMetricTagsSorted(dst []byte, mn *storage.MetricName) []byte {
sortMetricTags(mn.Tags)
sortMetricTags(mn)
return marshalMetricTagsFast(dst, mn.Tags)
}
func sortMetricTags(tags []storage.Tag) {
less := func(i, j int) bool {
return string(tags[i].Key) < string(tags[j].Key)
}
if sort.SliceIsSorted(tags, less) {
return
}
sort.Slice(tags, less)
}
func marshalBytesFast(dst []byte, s []byte) []byte {
dst = encoding.MarshalUint16(dst, uint16(len(s)))
dst = append(dst, s...)
@ -362,14 +352,14 @@ func unmarshalBytesFast(src []byte) ([]byte, []byte, error) {
func stringMetricName(mn *storage.MetricName) string {
var dst []byte
dst = append(dst, mn.MetricGroup...)
sortMetricTags(mn.Tags)
sortMetricTags(mn)
dst = appendStringMetricTags(dst, mn.Tags)
return string(dst)
}
func stringMetricTags(mn *storage.MetricName) string {
var dst []byte
sortMetricTags(mn.Tags)
sortMetricTags(mn)
dst = appendStringMetricTags(dst, mn.Tags)
return string(dst)
}
@ -429,3 +419,26 @@ func assertIdenticalTimestamps(tss []*timeseries, step int64) {
}
}
}
func sortMetricTags(mn *storage.MetricName) {
mts := (*metricTagsSorter)(mn)
if !sort.IsSorted(mts) {
sort.Sort(mts)
}
}
type metricTagsSorter storage.MetricName
func (mts *metricTagsSorter) Len() int {
return len(mts.Tags)
}
func (mts *metricTagsSorter) Less(i, j int) bool {
a := mts.Tags
return string(a[i].Key) < string(a[j].Key)
}
func (mts *metricTagsSorter) Swap(i, j int) {
a := mts.Tags
a[i], a[j] = a[j], a[i]
}