From c1e0ab11c67c9ddc105a8d3479503a6dc05c812e Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Fri, 31 Oct 2025 15:39:23 +0000 Subject: [PATCH] [PERF] TSDB: Speed up intersectPostings.Next Check if the next position is already a match, in which case we don't have to call `Seek`. Signed-off-by: Bryan Boreham --- tsdb/index/postings.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/tsdb/index/postings.go b/tsdb/index/postings.go index 0a0ac6a1fd..665a241c34 100644 --- a/tsdb/index/postings.go +++ b/tsdb/index/postings.go @@ -641,15 +641,28 @@ func (it *intersectPostings) Seek(target storage.SeriesRef) bool { } func (it *intersectPostings) Next() bool { - target := it.current - for _, p := range it.postings { + // Move forward the first Postings and take its value as the target to match. + if !it.postings[0].Next() { + return false + } + target := it.postings[0].At() + allEqual := true + for _, p := range it.postings[1:] { // Now move forward all the other ones and check if they match. if !p.Next() { return false } - if p.At() > target { - target = p.At() + at := p.At() + if at > target { // This one is past the target, so pick up a new target to Seek at the end. + target = at + allEqual = false + } else if at < target { // This one needs to Seek to the target, but carry on with other postings in case they have an even higher target. + allEqual = false } } + if allEqual { + it.current = target + return true + } return it.Seek(target) }