From 3f777bf16ffb019c970aee4bd550bfe3c38aa6bb Mon Sep 17 00:00:00 2001 From: Radu Ioan Fericean Date: Wed, 17 Aug 2016 14:16:11 +0300 Subject: [PATCH] cache improvements --- cache2go/lruttl.go | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/cache2go/lruttl.go b/cache2go/lruttl.go index 0afa04982..d96b81776 100644 --- a/cache2go/lruttl.go +++ b/cache2go/lruttl.go @@ -13,10 +13,6 @@ type Cache struct { // an item is evicted. Zero means no limit. maxEntries int - // OnEvicted optionally specificies a callback function to be - // executed when an entry is purged from the cache. - OnEvicted func(key string, value interface{}) - lruIndex *list.List ttlIndex []*list.Element cache map[string]*list.Element @@ -37,10 +33,10 @@ func NewLRUTTL(maxEntries int, expire time.Duration) *Cache { maxEntries: maxEntries, expiration: expire, lruIndex: list.New(), - ttlIndex: make([]*list.Element, 0), cache: make(map[string]*list.Element), } if c.expiration > 0 { + c.ttlIndex = make([]*list.Element, 0) go c.cleanExpired() } return c @@ -75,7 +71,9 @@ func (c *Cache) Set(key string, value interface{}) { if c.cache == nil { c.cache = make(map[string]*list.Element) c.lruIndex = list.New() - c.ttlIndex = make([]*list.Element, 0) + if c.expiration > 0 { + c.ttlIndex = make([]*list.Element, 0) + } } if e, ok := c.cache[key]; ok { @@ -89,7 +87,9 @@ func (c *Cache) Set(key string, value interface{}) { return } e := c.lruIndex.PushFront(&entry{key: key, value: value, timestamp: time.Now()}) - c.ttlIndex = append(c.ttlIndex, e) + if c.expiration > 0 { + c.ttlIndex = append(c.ttlIndex, e) + } c.cache[key] = e c.mu.Unlock() @@ -107,7 +107,7 @@ func (c *Cache) Get(key string) (value interface{}, ok bool) { } if e, hit := c.cache[key]; hit { c.lruIndex.MoveToFront(e) - e.Value.(*entry).timestamp = time.Now() + //e.Value.(*entry).timestamp = time.Now() don't update the timestamp on get' return e.Value.(*entry).value, true } return @@ -153,9 +153,6 @@ func (c *Cache) removeElement(e *list.Element) { } kv := e.Value.(*entry) delete(c.cache, kv.key) - if c.OnEvicted != nil { - c.OnEvicted(kv.key, kv.value) - } } // Len returns the number of items in the cache. @@ -173,6 +170,8 @@ func (c *Cache) Flush() { c.mu.Lock() defer c.mu.Unlock() c.lruIndex = list.New() - c.ttlIndex = make([]*list.Element, 0) + if c.expiration > 0 { + c.ttlIndex = make([]*list.Element, 0) + } c.cache = make(map[string]*list.Element) }