Only get the current time once in the DeleteExpired loop

This commit is contained in:
Patrick Mylund Nielsen 2015-11-30 13:39:27 -05:00
parent a45ed98559
commit 4e0d34ef00
1 changed files with 9 additions and 4 deletions

View File

@ -17,12 +17,16 @@ type Item struct {
Expiration time.Time Expiration time.Time
} }
// Returns true if the item has expired. func (item Item) expired(now time.Time) bool {
func (item Item) Expired() bool {
if item.Expiration == emptyTime { if item.Expiration == emptyTime {
return false return false
} }
return item.Expiration.Before(time.Now()) return item.Expiration.Before(now)
}
// Returns true if the item has expired.
func (item Item) Expired() bool {
return item.expired(time.Now())
} }
const ( const (
@ -868,9 +872,10 @@ type keyAndValue struct {
// Delete all expired items from the cache. // Delete all expired items from the cache.
func (c *cache) DeleteExpired() { func (c *cache) DeleteExpired() {
var evictedItems []keyAndValue var evictedItems []keyAndValue
now := time.Now()
c.mu.Lock() c.mu.Lock()
for k, v := range c.items { for k, v := range c.items {
if v.Expired() { if v.expired(now) {
ov, evicted := c.delete(k) ov, evicted := c.delete(k)
if evicted { if evicted {
evictedItems = append(evictedItems, keyAndValue{k, ov}) evictedItems = append(evictedItems, keyAndValue{k, ov})