From b6e22cd346eda9ad57c4b26d0bed10adf873a73f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Mierzwa?= Date: Mon, 7 Aug 2023 16:55:17 +0100 Subject: [PATCH] Short-cut common memChunk operations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit memChunk is a linked list, speed up some common operations when there's no need to iterate all elements on the list. Signed-off-by: Ɓukasz Mierzwa --- tsdb/head.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/tsdb/head.go b/tsdb/head.go index 2963d781d0..fefd31bd33 100644 --- a/tsdb/head.go +++ b/tsdb/head.go @@ -2265,6 +2265,10 @@ type memChunk struct { // len returns the length of memChunk list, including the element it was called on. func (mc *memChunk) len() (count int) { + if mc.prev == nil { + return 1 + } + elem := mc for elem != nil { count++ @@ -2276,6 +2280,9 @@ func (mc *memChunk) len() (count int) { // oldest returns the oldest element on the list. // For single element list this will be the same memChunk oldest() was called on. func (mc *memChunk) oldest() (elem *memChunk) { + if mc.prev == nil { + return mc + } elem = mc for elem.prev != nil { elem = elem.prev @@ -2288,6 +2295,9 @@ func (mc *memChunk) atOffset(offset int) (elem *memChunk) { if offset == 0 { return mc } + if offset == 1 { + return mc.prev + } if offset < 0 { return nil } @@ -2301,7 +2311,6 @@ func (mc *memChunk) atOffset(offset int) (elem *memChunk) { break } } - return elem }