Skip to content

Commit

Permalink
perf: Remove unneeded GetKey calls to the LRU cache (backport #890) (#…
Browse files Browse the repository at this point in the history
…899)

Co-authored-by: Dev Ojha <[email protected]>
  • Loading branch information
mergify[bot] and ValarDragon authored Mar 5, 2024
1 parent caa11ec commit e691ee9
Showing 1 changed file with 12 additions and 4 deletions.
16 changes: 12 additions & 4 deletions cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,16 @@ 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
return old.(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()
Expand All @@ -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
}
Expand All @@ -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
}

0 comments on commit e691ee9

Please sign in to comment.