Skip to content

Commit

Permalink
feat: use entry pool (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
scorix authored Dec 13, 2024
1 parent 33cf53c commit a38f3af
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions pkg/grib2/cache/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@ type Store interface {

// LRU Cache 实现
type lruStore struct {
mu sync.RWMutex
capacity int
cache map[int]*list.Element
lru *list.List
mu sync.RWMutex
capacity int
cache map[int]*list.Element
lru *list.List
entryPool sync.Pool
}

type entry struct {
Expand All @@ -29,6 +30,11 @@ func NewLRUStore(capacity int) Store {
capacity: capacity,
cache: make(map[int]*list.Element, capacity),
lru: list.New(),
entryPool: sync.Pool{
New: func() any {
return &entry{}
},
},
}
}

Expand Down Expand Up @@ -60,11 +66,15 @@ func (l *lruStore) Set(ctx context.Context, key int, value float32) {
if oldest != nil {
delete(l.cache, oldest.Value.(*entry).key)
l.lru.Remove(oldest)
l.entryPool.Put(oldest.Value)
}
}

// 添加新条目
elem := l.lru.PushFront(&entry{key: key, value: value})
newEntry := l.entryPool.Get().(*entry)
newEntry.key = key
newEntry.value = value
elem := l.lru.PushFront(newEntry)
l.cache[key] = elem
}

Expand Down

0 comments on commit a38f3af

Please sign in to comment.