Skip to content

Instantly share code, notes, and snippets.

@wjkoh
Last active February 12, 2025 15:18
Show Gist options
  • Save wjkoh/fbd491e2069e51ffefb0e4b9818c5ec2 to your computer and use it in GitHub Desktop.
Save wjkoh/fbd491e2069e51ffefb0e4b9818c5ec2 to your computer and use it in GitHub Desktop.
Go: A Simple TTL Cache Using time.AfterFunc()
package cache
import (
"sync"
"time"
)
type Cache[K comparable, V any] interface {
Set(K, V)
Get(K) (V, bool)
Remove(K)
}
type ttlCache[K comparable, V any] struct {
items map[K]V
ttl time.Duration
mu sync.Mutex
}
func NewTtl[K comparable, V any](ttl time.Duration) Cache[K, V] {
return &ttlCache[K, V]{
items: make(map[K]V),
ttl: ttl,
}
}
func (c *ttlCache[K, V]) Set(key K, value V) {
c.mu.Lock()
defer c.mu.Unlock()
c.items[key] = value
if c.ttl > 0 {
time.AfterFunc(c.ttl, func() { c.Remove(key) })
}
}
func (c *ttlCache[K, V]) Get(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
v, ok := c.items[key]
return v, ok
}
func (c *ttlCache[K, V]) Remove(key K) {
c.mu.Lock()
defer c.mu.Unlock()
delete(c.items, key)
}
@wjkoh
Copy link
Author

wjkoh commented Feb 12, 2025

goos: darwin
goarch: arm64
pkg: github.com/cowork-ai/docugpt/cache
cpu: Apple M2 Pro
BenchmarkCacheSet-10           	 9296667	       158.8 ns/op	     106 B/op	       0 allocs/op
BenchmarkCacheSetWithTtl-10    	 1545234	       781.1 ns/op	     166 B/op	       2 allocs/op
PASS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment