diff --git a/cache.go b/cache.go index df75728..54206fd 100644 --- a/cache.go +++ b/cache.go @@ -23,6 +23,8 @@ type Interface[K comparable, V any] interface { Keys() []K // Delete deletes the item with provided key from the cache. Delete(key K) + // Len returns the number of items in the cache. + Len() int } var ( @@ -253,6 +255,13 @@ func (c *Cache[K, V]) Delete(key K) { c.cache.Delete(key) } +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.cache.Len() +} + // Contains reports whether key is within cache. func (c *Cache[K, V]) Contains(key K) bool { c.mu.Lock() diff --git a/example_test.go b/example_test.go index 97ddbe0..7e2ae3e 100644 --- a/example_test.go +++ b/example_test.go @@ -123,6 +123,16 @@ func ExampleCache_Keys() { // [a b c] } +func ExampleCache_Len() { + c := cache.New(cache.AsLFU[string, int]()) + c.Set("a", 1) + c.Set("b", 1) + c.Set("c", 1) + fmt.Println(c.Len()) + // Output: + // 3 +} + func ExampleCache_Contains() { c := cache.New(cache.AsLRU[string, int]()) c.Set("a", 1) diff --git a/policy/simple/example_test.go b/policy/simple/example_test.go index bfe9c28..37f6a6a 100644 --- a/policy/simple/example_test.go +++ b/policy/simple/example_test.go @@ -2,6 +2,7 @@ package simple_test import ( "fmt" + "testing" "github.com/Code-Hex/go-generics-cache/policy/simple" ) @@ -47,3 +48,23 @@ func ExampleCache_Keys() { // bar // baz } + +func BenchmarkLenWithKeys(b *testing.B) { + c := simple.NewCache[string, int]() + c.Set("foo", 1) + c.Set("bar", 2) + c.Set("baz", 3) + for i := 0; i < b.N; i++ { + var _ = len(c.Keys()) + } +} + +func BenchmarkJustLen(b *testing.B) { + c := simple.NewCache[string, int]() + c.Set("foo", 1) + c.Set("bar", 2) + c.Set("baz", 3) + for i := 0; i < b.N; i++ { + var _ = c.Len() + } +} diff --git a/policy/simple/simple.go b/policy/simple/simple.go index 2ed4cdb..cb15ccd 100644 --- a/policy/simple/simple.go +++ b/policy/simple/simple.go @@ -59,3 +59,8 @@ func (c *Cache[K, _]) Keys() []K { func (c *Cache[K, V]) Delete(key K) { delete(c.items, key) } + +// Len returns the number of items in the cache. +func (c *Cache[K, V]) Len() int { + return len(c.items) +}