Simple LRU cache written in Go that allows you to store any type of element with a string-typed key.
Just go get this:
$ go get pedrolopesme/go-lru-cache
Once you have imported LRUCache
lib like this:
import (
...
"github.com/pedrolopesme/go-lru-cache"
)
You should initiate your cache bucket by defining a size to it:
func main() {
cache, err := NewLRUCache(10000) // after 10k items, it gonna drop the least accessed items.
if err != nil {
log.Fatal(err)
}
}
then you'll have both methods Set
and Get
available for usage.
cache.Set("my_key", myObj)
cachedObj := cache.Get("my_key") // cachedObj will be nil if it wasnt available on cache
This project comes with 3 handy targets on Makefile. They are:
Run all unit tests on the project
Run the benchmarks on the project. The current values on my development machine are:
❯ make bench
Running benchmark tests
go test -run=XXX -bench=.
goos: darwin
goarch: amd64
pkg: github.com/pedrolopesme/go-lru-cache
cpu: Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
BenchmarkLRUCache_OnlySettingKeys-4 2930050 403.8 ns/op
BenchmarkLRUCache_OnlyGettingKeys-4 9111232 132.6 ns/op
BenchmarkLRUCache_HalfSettingHalfGettingKeys_AllHits-4 3460792 334.7 ns/op
BenchmarkLRUCache_HalfSettingHalfGettingKeys_HalfHitsHalfMisses-4 4097424 292.9 ns/op
Run CPU and Memory profilers via pprof during a test of 10MM ops on the cache. The current output for both profilers are: cpu and memory.