From e691ee91f1ec637c6141cc9fae156a71de1ebc11 Mon Sep 17 00:00:00 2001 From: "mergify[bot]" <37929162+mergify[bot]@users.noreply.github.com> Date: Tue, 5 Mar 2024 23:00:09 +0100 Subject: [PATCH] perf: Remove unneeded GetKey calls to the LRU cache (backport #890) (#899) Co-authored-by: Dev Ojha --- cache/cache.go | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index 8b8097111..88bf19a2e 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -61,7 +61,8 @@ func New(maxElementCount int) Cache { } func (c *lruCache) Add(node Node) Node { - if e, exists := c.dict[string(node.GetKey())]; exists { + key := string(node.GetKey()) + if e, exists := c.dict[key]; exists { c.ll.MoveToFront(e) old := e.Value e.Value = node @@ -69,7 +70,7 @@ func (c *lruCache) Add(node Node) Node { } elem := c.ll.PushFront(node) - c.dict[string(node.GetKey())] = elem + c.dict[key] = elem if c.ll.Len() > c.maxElementCount { oldest := c.ll.Back() @@ -96,8 +97,9 @@ func (c *lruCache) Len() int { } func (c *lruCache) Remove(key []byte) Node { - if elem, exists := c.dict[string(key)]; exists { - return c.remove(elem) + keyS := string(key) + if elem, exists := c.dict[keyS]; exists { + return c.removeWithKey(elem, keyS) } return nil } @@ -107,3 +109,9 @@ func (c *lruCache) remove(e *list.Element) Node { delete(c.dict, ibytes.UnsafeBytesToStr(removed.GetKey())) return removed } + +func (c *lruCache) removeWithKey(e *list.Element, key string) Node { + removed := c.ll.Remove(e).(Node) + delete(c.dict, key) + return removed +}