Improve speed of the cache module.

This commit is contained in:
2024-10-13 18:00:43 +01:00
parent 0be45f06a5
commit 4972b21373
+14 -10
View File
@@ -8,7 +8,7 @@ import (
// CacheItem represents an item in the cache // CacheItem represents an item in the cache
type CacheItem struct { type CacheItem struct {
Value interface{} Value interface{}
ExpiresAt time.Time ExpiresAt int64 // Changed to int64 for faster comparisons
} }
// Cache is a simple in-memory cache // Cache is a simple in-memory cache
@@ -27,43 +27,47 @@ func NewCache() *Cache {
// Set adds an item to the cache // Set adds an item to the cache
func (c *Cache) Set(key string, value interface{}, expiration time.Duration) { func (c *Cache) Set(key string, value interface{}, expiration time.Duration) {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() // Removed defer for slightly better performance
c.items[key] = CacheItem{ c.items[key] = CacheItem{
Value: value, 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 // Get retrieves an item from the cache
func (c *Cache) Get(key string) (interface{}, bool) { func (c *Cache) Get(key string) (interface{}, bool) {
c.mutex.RLock() c.mutex.RLock()
defer c.mutex.RUnlock()
item, found := c.items[key] item, found := c.items[key]
if !found { if !found {
c.mutex.RUnlock()
return nil, false return nil, false
} }
if time.Now().After(item.ExpiresAt) { if time.Now().UnixNano() > item.ExpiresAt {
delete(c.items, key) c.mutex.RUnlock()
// Use a separate goroutine to delete expired items to avoid blocking
go c.Delete(key)
return nil, false return nil, false
} }
c.mutex.RUnlock()
return item.Value, true return item.Value, true
} }
// Delete removes an item from the cache // Delete removes an item from the cache
func (c *Cache) Delete(key string) { func (c *Cache) Delete(key string) {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock()
delete(c.items, key) delete(c.items, key)
c.mutex.Unlock()
} }
// Cleanup removes expired items from the cache // Cleanup removes expired items from the cache
func (c *Cache) Cleanup() { func (c *Cache) Cleanup() {
c.mutex.Lock() c.mutex.Lock()
defer c.mutex.Unlock() now := time.Now().UnixNano()
now := time.Now()
for key, item := range c.items { for key, item := range c.items {
if now.After(item.ExpiresAt) { if now > item.ExpiresAt {
delete(c.items, key) delete(c.items, key)
} }
} }
c.mutex.Unlock()
} }