From 836d04893ce2b7dadb2e81bfc1803a077fe5d6ca Mon Sep 17 00:00:00 2001 From: Axel PREL Date: Thu, 27 Jun 2024 11:45:18 +0200 Subject: [PATCH] DeleteExpired: avoid unnecessary m.Cache.Get() --- cache.go | 14 +++++--------- expiration.go | 5 +++-- 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/cache.go b/cache.go index e40a8a3..c7e8b9f 100644 --- a/cache.go +++ b/cache.go @@ -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 } diff --git a/expiration.go b/expiration.go index 44ee4ea..ee5d9c2 100644 --- a/expiration.go +++ b/expiration.go @@ -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) {