From 0e1e7441e45f5ea208629541c5db455a3f80eaae Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Fri, 31 Oct 2025 15:28:15 +0000 Subject: [PATCH] [PERF] TSDB: ListPostings: check next item before binary search It is fairly common that the next item is the one we want, and cheap to check. We could also start the binary search one position on, but strangely that slows it down. Signed-off-by: Bryan Boreham --- tsdb/index/postings.go | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tsdb/index/postings.go b/tsdb/index/postings.go index d5a17c3daa..0a0ac6a1fd 100644 --- a/tsdb/index/postings.go +++ b/tsdb/index/postings.go @@ -851,15 +851,17 @@ func (it *ListPostings) Seek(x storage.SeriesRef) bool { return false } - // Do binary search between current position and end. - i, _ := slices.BinarySearch(it.list, x) - if i < len(it.list) { - it.cur = it.list[i] - it.list = it.list[i+1:] - return true + i := 0 // Check the next item in the list, otherwise binary search between current position and end. + if it.list[0] < x { + i, _ = slices.BinarySearch(it.list, x) + if i >= len(it.list) { // Off the end - terminate the iterator. + it.list = nil + return false + } } - it.list = nil - return false + it.cur = it.list[i] + it.list = it.list[i+1:] + return true } func (*ListPostings) Err() error {