Skip to content

Commit

Permalink
DeleteExpired: avoid unnecessary m.Cache.Get()
Browse files Browse the repository at this point in the history
  • Loading branch information
AxelPrel committed Jun 27, 2024
1 parent 064ff83 commit 836d048
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 11 deletions.
14 changes: 5 additions & 9 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,16 +249,12 @@ func (c *Cache[K, V]) DeleteExpired() {
if c.expManager.len() == 0 {
return false
}
key := c.expManager.pop()
// if is expired, delete it and return nil instead
item, ok := c.cache.Get(key)
if ok {
if item.Expired() {
c.cache.Delete(key)
return true
}
c.expManager.update(key, item.Expiration)
key, expiration := c.expManager.pop()
if nowFunc().After(expiration) {
c.cache.Delete(key)
return true
}
c.expManager.update(key, expiration)
return false
}

Expand Down
5 changes: 3 additions & 2 deletions expiration.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@ func (m *expirationManager[K]) len() int {
return m.queue.Len()
}

func (m *expirationManager[K]) pop() K {
func (m *expirationManager[K]) pop() (K, time.Time) {
v := heap.Pop(&m.queue)
key := v.(*expirationKey[K]).key
exp := v.(*expirationKey[K]).expiration
delete(m.mapping, key)
return key
return key, exp
}

func (m *expirationManager[K]) remove(key K) {
Expand Down

0 comments on commit 836d048

Please sign in to comment.