Replace sort.Slice with faster slices.SortFunc

The generic version is more efficient.

Signed-off-by: Bryan Boreham <bjboreham@gmail.com>
This commit is contained in:
Bryan Boreham 2023-07-02 22:16:26 +00:00
parent 031d22df9e
commit 5255bf06ad
12 changed files with 47 additions and 47 deletions

View file

@ -23,7 +23,6 @@ import (
"path/filepath" "path/filepath"
"runtime" "runtime"
"runtime/pprof" "runtime/pprof"
"sort"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -34,6 +33,7 @@ import (
"github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc" "github.com/prometheus/prometheus/tsdb/chunkenc"
"github.com/prometheus/prometheus/tsdb/index" "github.com/prometheus/prometheus/tsdb/index"
"golang.org/x/exp/slices"
"github.com/alecthomas/units" "github.com/alecthomas/units"
"github.com/go-kit/log" "github.com/go-kit/log"
@ -447,7 +447,7 @@ func analyzeBlock(path, blockID string, limit int, runExtended bool) error {
postingInfos := []postingInfo{} postingInfos := []postingInfo{}
printInfo := func(postingInfos []postingInfo) { printInfo := func(postingInfos []postingInfo) {
sort.Slice(postingInfos, func(i, j int) bool { return postingInfos[i].metric > postingInfos[j].metric }) slices.SortFunc(postingInfos, func(a, b postingInfo) bool { return a.metric > b.metric })
for i, pc := range postingInfos { for i, pc := range postingInfos {
if i >= limit { if i >= limit {

View file

@ -19,7 +19,6 @@ import (
"fmt" "fmt"
"math" "math"
"net/url" "net/url"
"sort"
"sync" "sync"
"time" "time"
@ -30,6 +29,7 @@ import (
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/codes"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/rulefmt" "github.com/prometheus/prometheus/model/rulefmt"
@ -490,10 +490,9 @@ func (g *Group) AlertingRules() []*AlertingRule {
alerts = append(alerts, alertingRule) alerts = append(alerts, alertingRule)
} }
} }
sort.Slice(alerts, func(i, j int) bool { slices.SortFunc(alerts, func(a, b *AlertingRule) bool {
return alerts[i].State() > alerts[j].State() || return a.State() > b.State() ||
(alerts[i].State() == alerts[j].State() && (a.State() == b.State() && a.Name() < b.Name())
alerts[i].Name() < alerts[j].Name())
}) })
return alerts return alerts
} }
@ -1189,11 +1188,11 @@ func (m *Manager) RuleGroups() []*Group {
rgs = append(rgs, g) rgs = append(rgs, g)
} }
sort.Slice(rgs, func(i, j int) bool { slices.SortFunc(rgs, func(a, b *Group) bool {
if rgs[i].file != rgs[j].file { if a.file != b.file {
return rgs[i].file < rgs[j].file return a.file < b.file
} }
return rgs[i].name < rgs[j].name return a.name < b.name
}) })
return rgs return rgs

View file

@ -23,7 +23,6 @@ import (
"math" "math"
"net/http" "net/http"
"reflect" "reflect"
"sort"
"strconv" "strconv"
"sync" "sync"
"time" "time"
@ -35,6 +34,7 @@ import (
config_util "github.com/prometheus/common/config" config_util "github.com/prometheus/common/config"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
"github.com/prometheus/common/version" "github.com/prometheus/common/version"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/discovery/targetgroup" "github.com/prometheus/prometheus/discovery/targetgroup"
@ -720,8 +720,8 @@ func mutateSampleLabels(lset labels.Labels, target *Target, honor bool, rc []*re
} }
func resolveConflictingExposedLabels(lb *labels.Builder, conflictingExposedLabels []labels.Label) { func resolveConflictingExposedLabels(lb *labels.Builder, conflictingExposedLabels []labels.Label) {
sort.SliceStable(conflictingExposedLabels, func(i, j int) bool { slices.SortStableFunc(conflictingExposedLabels, func(a, b labels.Label) bool {
return len(conflictingExposedLabels[i].Name) < len(conflictingExposedLabels[j].Name) return len(a.Name) < len(b.Name)
}) })
for _, l := range conflictingExposedLabels { for _, l := range conflictingExposedLabels {

View file

@ -16,12 +16,12 @@ package remote
import ( import (
"context" "context"
"net/http" "net/http"
"sort"
"sync" "sync"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/model/labels" "github.com/prometheus/prometheus/model/labels"
@ -92,8 +92,8 @@ func (h *readHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Value: value, Value: value,
}) })
} }
sort.Slice(sortedExternalLabels, func(i, j int) bool { slices.SortFunc(sortedExternalLabels, func(a, b prompb.Label) bool {
return sortedExternalLabels[i].Name < sortedExternalLabels[j].Name return a.Name < b.Name
}) })
responseType, err := NegotiateResponseType(req.AcceptedResponseTypes) responseType, err := NegotiateResponseType(req.AcceptedResponseTypes)

View file

@ -20,7 +20,6 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"time" "time"
"github.com/go-kit/log" "github.com/go-kit/log"
@ -28,6 +27,7 @@ import (
"github.com/oklog/ulid" "github.com/oklog/ulid"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/storage" "github.com/prometheus/prometheus/storage"
"github.com/prometheus/prometheus/tsdb/chunkenc" "github.com/prometheus/prometheus/tsdb/chunkenc"
@ -200,8 +200,8 @@ func (c *LeveledCompactor) Plan(dir string) ([]string, error) {
} }
func (c *LeveledCompactor) plan(dms []dirMeta) ([]string, error) { func (c *LeveledCompactor) plan(dms []dirMeta) ([]string, error) {
sort.Slice(dms, func(i, j int) bool { slices.SortFunc(dms, func(a, b dirMeta) bool {
return dms[i].meta.MinTime < dms[j].meta.MinTime return a.meta.MinTime < b.meta.MinTime
}) })
res := c.selectOverlappingDirs(dms) res := c.selectOverlappingDirs(dms)
@ -380,8 +380,8 @@ func CompactBlockMetas(uid ulid.ULID, blocks ...*BlockMeta) *BlockMeta {
for s := range sources { for s := range sources {
res.Compaction.Sources = append(res.Compaction.Sources, s) res.Compaction.Sources = append(res.Compaction.Sources, s)
} }
sort.Slice(res.Compaction.Sources, func(i, j int) bool { slices.SortFunc(res.Compaction.Sources, func(a, b ulid.ULID) bool {
return res.Compaction.Sources[i].Compare(res.Compaction.Sources[j]) < 0 return a.Compare(b) < 0
}) })
res.MinTime = mint res.MinTime = mint

View file

@ -22,7 +22,6 @@ import (
"math" "math"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
@ -34,6 +33,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"go.uber.org/atomic" "go.uber.org/atomic"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
"github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/config"
@ -579,8 +579,8 @@ func (db *DBReadOnly) Blocks() ([]BlockReader, error) {
return nil, nil return nil, nil
} }
sort.Slice(loadable, func(i, j int) bool { slices.SortFunc(loadable, func(a, b *Block) bool {
return loadable[i].Meta().MinTime < loadable[j].Meta().MinTime return a.Meta().MinTime < b.Meta().MinTime
}) })
blockMetas := make([]BlockMeta, 0, len(loadable)) blockMetas := make([]BlockMeta, 0, len(loadable))
@ -1445,8 +1445,8 @@ func (db *DB) reloadBlocks() (err error) {
} }
db.metrics.blocksBytes.Set(float64(blocksSize)) db.metrics.blocksBytes.Set(float64(blocksSize))
sort.Slice(toLoad, func(i, j int) bool { slices.SortFunc(toLoad, func(a, b *Block) bool {
return toLoad[i].Meta().MinTime < toLoad[j].Meta().MinTime return a.Meta().MinTime < b.Meta().MinTime
}) })
// Swap new blocks first for subsequently created readers to be seen. // Swap new blocks first for subsequently created readers to be seen.
@ -1515,8 +1515,8 @@ func deletableBlocks(db *DB, blocks []*Block) map[ulid.ULID]struct{} {
// Sort the blocks by time - newest to oldest (largest to smallest timestamp). // Sort the blocks by time - newest to oldest (largest to smallest timestamp).
// This ensures that the retentions will remove the oldest blocks. // This ensures that the retentions will remove the oldest blocks.
sort.Slice(blocks, func(i, j int) bool { slices.SortFunc(blocks, func(a, b *Block) bool {
return blocks[i].Meta().MaxTime > blocks[j].Meta().MaxTime return a.Meta().MaxTime > b.Meta().MaxTime
}) })
for _, block := range blocks { for _, block := range blocks {

View file

@ -15,11 +15,11 @@ package tsdb
import ( import (
"context" "context"
"sort"
"sync" "sync"
"unicode/utf8" "unicode/utf8"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/config" "github.com/prometheus/prometheus/config"
"github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/exemplar"
@ -185,8 +185,8 @@ func (ce *CircularExemplarStorage) Select(start, end int64, matchers ...[]*label
} }
} }
sort.Slice(ret, func(i, j int) bool { slices.SortFunc(ret, func(a, b exemplar.QueryResult) bool {
return labels.Compare(ret[i].SeriesLabels, ret[j].SeriesLabels) < 0 return labels.Compare(a.SeriesLabels, b.SeriesLabels) < 0
}) })
return ret, nil return ret, nil

View file

@ -137,8 +137,8 @@ func (h *headIndexReader) SortedPostings(p index.Postings) index.Postings {
return index.ErrPostings(errors.Wrap(err, "expand postings")) return index.ErrPostings(errors.Wrap(err, "expand postings"))
} }
sort.Slice(series, func(i, j int) bool { slices.SortFunc(series, func(a, b *memSeries) bool {
return labels.Compare(series[i].lset, series[j].lset) < 0 return labels.Compare(a.lset, b.lset) < 0
}) })
// Convert back to list. // Convert back to list.

View file

@ -107,11 +107,11 @@ func (p *MemPostings) SortedKeys() []labels.Label {
} }
p.mtx.RUnlock() p.mtx.RUnlock()
sort.Slice(keys, func(i, j int) bool { slices.SortFunc(keys, func(a, b labels.Label) bool {
if keys[i].Name != keys[j].Name { if a.Name != b.Name {
return keys[i].Name < keys[j].Name return a.Name < b.Name
} }
return keys[i].Value < keys[j].Value return a.Value < b.Value
}) })
return keys return keys
} }

View file

@ -15,7 +15,8 @@ package index
import ( import (
"math" "math"
"sort"
"golang.org/x/exp/slices"
) )
// Stat holds values for a single cardinality statistic. // Stat holds values for a single cardinality statistic.
@ -62,8 +63,8 @@ func (m *maxHeap) push(item Stat) {
} }
func (m *maxHeap) get() []Stat { func (m *maxHeap) get() []Stat {
sort.Slice(m.Items, func(i, j int) bool { slices.SortFunc(m.Items, func(a, b Stat) bool {
return m.Items[i].Count > m.Items[j].Count return a.Count > b.Count
}) })
return m.Items return m.Items
} }

View file

@ -20,13 +20,13 @@ import (
"math" "math"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strconv" "strconv"
"strings" "strings"
"github.com/go-kit/log" "github.com/go-kit/log"
"github.com/go-kit/log/level" "github.com/go-kit/log/level"
"github.com/pkg/errors" "github.com/pkg/errors"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/tsdb/chunks" "github.com/prometheus/prometheus/tsdb/chunks"
tsdb_errors "github.com/prometheus/prometheus/tsdb/errors" tsdb_errors "github.com/prometheus/prometheus/tsdb/errors"
@ -374,8 +374,8 @@ func listCheckpoints(dir string) (refs []checkpointRef, err error) {
refs = append(refs, checkpointRef{name: fi.Name(), index: idx}) refs = append(refs, checkpointRef{name: fi.Name(), index: idx})
} }
sort.Slice(refs, func(i, j int) bool { slices.SortFunc(refs, func(a, b checkpointRef) bool {
return refs[i].index < refs[j].index return a.index < b.index
}) })
return refs, nil return refs, nil

View file

@ -22,7 +22,6 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"sort"
"strconv" "strconv"
"sync" "sync"
"time" "time"
@ -32,6 +31,7 @@ import (
"github.com/golang/snappy" "github.com/golang/snappy"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
"golang.org/x/exp/slices"
"github.com/prometheus/prometheus/tsdb/fileutil" "github.com/prometheus/prometheus/tsdb/fileutil"
) )
@ -859,8 +859,8 @@ func listSegments(dir string) (refs []segmentRef, err error) {
} }
refs = append(refs, segmentRef{name: fn, index: k}) refs = append(refs, segmentRef{name: fn, index: k})
} }
sort.Slice(refs, func(i, j int) bool { slices.SortFunc(refs, func(a, b segmentRef) bool {
return refs[i].index < refs[j].index return a.index < b.index
}) })
for i := 0; i < len(refs)-1; i++ { for i := 0; i < len(refs)-1; i++ {
if refs[i].index+1 != refs[i+1].index { if refs[i].index+1 != refs[i+1].index {