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
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()
}