Skip to content

Commit

Permalink
optimized methods
Browse files Browse the repository at this point in the history
  • Loading branch information
alserov committed Jul 25, 2024
1 parent 5044682 commit 8ec07ac
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
22 changes: 14 additions & 8 deletions lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,21 @@ func (c *lru) Close() {
// Get retrieves value by its id, returns false if not found
func (c *lru) Get(ctx context.Context, key string) (any, bool) {
c.mu.RLock()
defer c.mu.RUnlock()

val, ok := c.vals[key]
if !ok {
return nil, false
c.mu.RUnlock()

if ok {
c.updatePos(val)
return val.val, true
}

return nil, false
}

func (c *lru) updatePos(val *lruNode) {
c.mu.Lock()
defer c.mu.Unlock()

if val != c.head {
if len(c.vals) == 2 {
c.head, c.tail = c.tail, c.head
Expand All @@ -75,13 +83,11 @@ func (c *lru) Get(ctx context.Context, key string) (any, bool) {
c.head = val
}
}

return val.val, true
}

func (c *lru) Set(ctx context.Context, key string, val any) {
c.mu.Lock()
defer c.mu.Unlock()
c.mu.RLock()
defer c.mu.RUnlock()

if _, ok := c.vals[key]; ok {
return
Expand Down
4 changes: 2 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@ func main() {
```text
cpu: Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz
BenchmarkLRUGet
BenchmarkLRUGet-12 70945466 16.89 ns/op
BenchmarkLRUGet-12 87289867 13.49 ns/op
```


#### Set
```text
cpu: Intel(R) Core(TM) i5-10400F CPU @ 2.90GHz
BenchmarkLRUSet
BenchmarkLRUSet-12 40799257 29.68 ns/op
BenchmarkLRUSet-12 59914920 19.65 ns/op
```

### LFU
Expand Down

0 comments on commit 8ec07ac

Please sign in to comment.