Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: Remove unneeded GetKey calls to the LRU cache #890

Merged
merged 2 commits into from
Mar 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This undoes the zero byteslice->string Go map lookup optimization.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh wow, didn't know about this compiler optimization.

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
}
Loading