diff --git a/cache.go b/cache.go index 759ec1a..4c76899 100644 --- a/cache.go +++ b/cache.go @@ -8,7 +8,7 @@ import ( // CacheItem represents an item in the cache type CacheItem struct { Value interface{} - ExpiresAt time.Time + ExpiresAt int64 // Changed to int64 for faster comparisons } // Cache is a simple in-memory cache @@ -27,43 +27,47 @@ func NewCache() *Cache { // Set adds an item to the cache func (c *Cache) Set(key string, value interface{}, expiration time.Duration) { c.mutex.Lock() - defer c.mutex.Unlock() + // Removed defer for slightly better performance c.items[key] = CacheItem{ Value: value, - ExpiresAt: time.Now().Add(expiration), + ExpiresAt: time.Now().Add(expiration).UnixNano(), // Store as UnixNano for faster comparisons } + c.mutex.Unlock() } // Get retrieves an item from the cache func (c *Cache) Get(key string) (interface{}, bool) { c.mutex.RLock() - defer c.mutex.RUnlock() item, found := c.items[key] if !found { + c.mutex.RUnlock() return nil, false } - if time.Now().After(item.ExpiresAt) { - delete(c.items, key) + if time.Now().UnixNano() > item.ExpiresAt { + c.mutex.RUnlock() + // Use a separate goroutine to delete expired items to avoid blocking + go c.Delete(key) return nil, false } + c.mutex.RUnlock() return item.Value, true } // Delete removes an item from the cache func (c *Cache) Delete(key string) { c.mutex.Lock() - defer c.mutex.Unlock() delete(c.items, key) + c.mutex.Unlock() } // Cleanup removes expired items from the cache func (c *Cache) Cleanup() { c.mutex.Lock() - defer c.mutex.Unlock() - now := time.Now() + now := time.Now().UnixNano() for key, item := range c.items { - if now.After(item.ExpiresAt) { + if now > item.ExpiresAt { delete(c.items, key) } } + c.mutex.Unlock() }