diff --git a/cache/lru_cache.go b/cache/lru_cache.go index 629d6bd..ae04138 100644 --- a/cache/lru_cache.go +++ b/cache/lru_cache.go @@ -10,6 +10,10 @@ import ( "github.com/ava-labs/gecko/ids" ) +const ( + minCacheSize = 32 +) + type entry struct { Key ids.ID Value interface{} @@ -59,7 +63,7 @@ func (c *LRU) Flush() { func (c *LRU) init() { if c.entryMap == nil { - c.entryMap = make(map[[32]byte]*list.Element) + c.entryMap = make(map[[32]byte]*list.Element, minCacheSize) } if c.entryList == nil { c.entryList = list.New() @@ -134,6 +138,6 @@ func (c *LRU) evict(key ids.ID) { func (c *LRU) flush() { c.init() - c.entryMap = make(map[[32]byte]*list.Element) + c.entryMap = make(map[[32]byte]*list.Element, minCacheSize) c.entryList = list.New() } diff --git a/cache/lru_cache_benchmark_test.go b/cache/lru_cache_benchmark_test.go new file mode 100644 index 0000000..6bdbaf8 --- /dev/null +++ b/cache/lru_cache_benchmark_test.go @@ -0,0 +1,53 @@ +package cache + +import ( + "crypto/rand" + "testing" + + "github.com/ava-labs/gecko/ids" +) + +func BenchmarkLRUCachePutSmall(b *testing.B) { + smallLen := 5 + cache := &LRU{Size: smallLen} + for n := 0; n < b.N; n++ { + for i := 0; i < smallLen; i++ { + var idBytes [32]byte + rand.Read(idBytes[:]) + cache.Put(ids.NewID(idBytes), n) + } + b.StopTimer() + cache.Flush() + b.StartTimer() + } +} + +func BenchmarkLRUCachePutMedium(b *testing.B) { + mediumLen := 250 + cache := &LRU{Size: mediumLen} + for n := 0; n < b.N; n++ { + for i := 0; i < mediumLen; i++ { + var idBytes [32]byte + rand.Read(idBytes[:]) + cache.Put(ids.NewID(idBytes), n) + } + b.StopTimer() + cache.Flush() + b.StartTimer() + } +} + +func BenchmarkLRUCachePutLarge(b *testing.B) { + largeLen := 10000 + cache := &LRU{Size: largeLen} + for n := 0; n < b.N; n++ { + for i := 0; i < largeLen; i++ { + var idBytes [32]byte + rand.Read(idBytes[:]) + cache.Put(ids.NewID(idBytes), n) + } + b.StopTimer() + cache.Flush() + b.StartTimer() + } +}