Memoization Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Memoization runs in O(1) cached time and O(n) space, in Go as in every other language.
- ✓A map guarded by sync.RWMutex, or sync.Map when the workload is read-heavy with stable keys.
- ✓Reach for singleflight whenever the memoized work is expensive and callers are concurrent, a cold cache under load otherwise starts N identical database queries, which is the thundering-herd failure.
- ✓The Go trap: The obvious double-checked pattern is a data race in Go, not a benign one: taking an RLock, seeing a miss, dropping it, taking the write lock, and inserting means two goroutines both compute.
- ✓sync.Map avoids lock contention for repeat reads via a read-only copy but is significantly SLOWER than a plain mutex-guarded map for write-heavy workloads, the standard library documents this explicitly.
What Memoization actually is
Memoization in Go: what you actually reach for
Go implementation
package memo
import (
"sync"
"golang.org/x/sync/singleflight"
)
type Memo struct {
mu sync.RWMutex
cache map[string]int
group singleflight.Group // collapses concurrent identical misses
}
func New() *Memo {
return &Memo{cache: make(map[string]int)}
}
func (m *Memo) Get(key string, compute func() (int, error)) (int, error) {
m.mu.RLock()
if v, ok := m.cache[key]; ok {
m.mu.RUnlock()
return v, nil
}
m.mu.RUnlock()
// Ten goroutines missing the same key run compute ONCE.
v, err, _ := m.group.Do(key, func() (any, error) {
value, err := compute()
if err != nil {
return nil, err
}
m.mu.Lock()
m.cache[key] = value
m.mu.Unlock()
return value, nil
})
if err != nil {
return 0, err
}
return v.(int), nil
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1) cached
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for Memoization?
A map guarded by sync.RWMutex, or sync.Map when the workload is read-heavy with stable keys. The genuinely Go-specific tool is golang.org/x/sync/singleflight, which collapses concurrent identical misses into ONE execution and hands the same result to every waiting caller. sync.Once memoizes a single value with no lock on the fast path.
What is the most common Go mistake when implementing Memoization?
The obvious double-checked pattern is a data race in Go, not a benign one: taking an RLock, seeing a miss, dropping it, taking the write lock, and inserting means two goroutines both compute. That is merely wasteful for a pure function and catastrophic if the work is a rate-limited API call. Separately, sync.Map returns any, so every read costs a type assertion.
How does Memoization actually perform in Go?
sync.Map avoids lock contention for repeat reads via a read-only copy but is significantly SLOWER than a plain mutex-guarded map for write-heavy workloads, the standard library documents this explicitly. singleflight adds one map lookup and a WaitGroup per miss and nothing at all on hits. Sharding a mutex-guarded map by hash across 32 buckets usually beats both. Time complexity is O(1) cached and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.