Skip to content

Commit

Permalink
updated methods, made faster set, but slowered get, fixed mutexes lock
Browse files Browse the repository at this point in the history
  • Loading branch information
alserov committed Jul 25, 2024
1 parent f516c0f commit e923e5e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 18 deletions.
40 changes: 24 additions & 16 deletions lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,37 +46,44 @@ 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
}

if len(c.vals) == 2 {
c.head, c.tail = c.tail, c.head
c.head.next = c.tail
c.tail.prev = c.head
} else {
if val.prev != nil {
c.vals[key].prev.next = c.vals[key].next
}

if val.next != nil {
c.vals[key].next.prev = c.vals[key].prev
if val != c.head {
if len(c.vals) == 2 {
c.head, c.tail = c.tail, c.head
c.head.next = c.tail
c.tail.prev = c.head
} else {
if c.tail != nil {
if val.prev != nil {
c.vals[key].prev.next = val.next
}
if val.next != nil {
c.vals[key].next.prev = val.prev
}

if val == c.tail {
c.tail = c.tail.prev
}
}
}
c.mu.RUnlock()

return val.val, true
}

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

if _, ok := c.vals[key]; ok {
return
}

node := &lruNode{
prev: nil,
next: c.head,
key: key,
val: val,
Expand All @@ -87,13 +94,14 @@ func (c *lru) Set(ctx context.Context, key string, val any) {
}

c.vals[key] = node
c.head = c.vals[key]
c.head = node

if len(c.vals) == c.limit {
if c.tail != nil {
delete(c.vals, c.tail.key)
c.tail = c.tail.prev
} else {
c.head = nil
}
}
c.mu.Unlock()
}
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 137647732 8.623 ns/op
BenchmarkLRUGet-12 70945466 16.89 ns/op
```


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

### LFU
Expand Down

0 comments on commit e923e5e

Please sign in to comment.