Senior
What cache eviction strategy is best to use?
sobes.tech AI
Answer from AI
The choice of cache eviction strategy depends on specific requirements and the nature of the load. The most common strategies:
- LRU (Least Recently Used) — evicts the least recently used items. Suitable when the same data is frequently repeated.
- LFU (Least Frequently Used) — evicts the least frequently accessed items. Effective if access frequency is important.
- FIFO (First In First Out) — evicts the oldest items regardless of usage.
In Go, LRU is often used because it balances freshness and access frequency well. For example, LRU caches are implemented in packages like golang.org/x/exp/slices or third-party libraries.
Example of using an LRU cache with the hashicorp/golang-lru library:
import (
"github.com/hashicorp/golang-lru"
"log"
)
func main() {
cache, err := lru.New(128) // cache size of 128 items
if err != nil {
log.Fatal(err)
}
cache.Add("key1", "value1")
if val, ok := cache.Get("key1"); ok {
fmt.Println(val) // value1
}
}
If the cache is used in a multithreaded environment, consider thread safety and choose appropriate implementations.