Skip to content

Commit 7087cb7

Browse files
guanwjefferai
authored andcommitted
remove defer keyword to avoid overhead (#53)
1 parent 20f1fb7 commit 7087cb7

File tree

1 file changed

+18
-12
lines changed

1 file changed

+18
-12
lines changed

lru.go

+18-12
Original file line numberDiff line numberDiff line change
@@ -40,31 +40,35 @@ func (c *Cache) Purge() {
4040
// Add adds a value to the cache. Returns true if an eviction occurred.
4141
func (c *Cache) Add(key, value interface{}) (evicted bool) {
4242
c.lock.Lock()
43-
defer c.lock.Unlock()
44-
return c.lru.Add(key, value)
43+
evicted = c.lru.Add(key, value)
44+
c.lock.Unlock()
45+
return evicted
4546
}
4647

4748
// Get looks up a key's value from the cache.
4849
func (c *Cache) Get(key interface{}) (value interface{}, ok bool) {
4950
c.lock.Lock()
50-
defer c.lock.Unlock()
51-
return c.lru.Get(key)
51+
value, ok = c.lru.Get(key)
52+
c.lock.Unlock()
53+
return value, ok
5254
}
5355

5456
// Contains checks if a key is in the cache, without updating the
5557
// recent-ness or deleting it for being stale.
5658
func (c *Cache) Contains(key interface{}) bool {
5759
c.lock.RLock()
58-
defer c.lock.RUnlock()
59-
return c.lru.Contains(key)
60+
containKey := c.lru.Contains(key)
61+
c.lock.RUnlock()
62+
return containKey
6063
}
6164

6265
// Peek returns the key value (or undefined if not found) without updating
6366
// the "recently used"-ness of the key.
6467
func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) {
6568
c.lock.RLock()
66-
defer c.lock.RUnlock()
67-
return c.lru.Peek(key)
69+
value, ok = c.lru.Peek(key)
70+
c.lock.RUnlock()
71+
return value, ok
6872
}
6973

7074
// ContainsOrAdd checks if a key is in the cache without updating the
@@ -98,13 +102,15 @@ func (c *Cache) RemoveOldest() {
98102
// Keys returns a slice of the keys in the cache, from oldest to newest.
99103
func (c *Cache) Keys() []interface{} {
100104
c.lock.RLock()
101-
defer c.lock.RUnlock()
102-
return c.lru.Keys()
105+
keys := c.lru.Keys()
106+
c.lock.RUnlock()
107+
return keys
103108
}
104109

105110
// Len returns the number of items in the cache.
106111
func (c *Cache) Len() int {
107112
c.lock.RLock()
108-
defer c.lock.RUnlock()
109-
return c.lru.Len()
113+
length := c.lru.Len()
114+
c.lock.RUnlock()
115+
return length
110116
}

0 commit comments

Comments
 (0)