Memoization Implementation in C#
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 C# as in every other language.
- ✓ConcurrentDictionary<TKey, TValue>.GetOrAdd is the obvious tool and Lazy<T> is the one that makes it correct.
- ✓Store Lazy<TValue> as the dictionary VALUE, not TValue. GetOrAdd then races only on constructing the cheap Lazy wrapper, and Lazy's default thread-safety mode guarantees the expensive factory runs exactly once no matter how many threads arrive together.
- ✓The C# trap: ConcurrentDictionary.GetOrAdd does NOT guarantee the value factory runs only once. It is documented as being invoked outside the lock, so under contention several threads run it concurrently and all but one result is discarded.
- ✓The Lazy<T> wrapper costs one small allocation per key plus a volatile read on every subsequent hit, which is negligible against any factory worth memoizing.
What Memoization actually is
Memoization in C#: what you actually reach for
C# implementation
using System;
using System.Collections.Concurrent;
public sealed class Memoizer<TKey, TValue> where TKey : notnull
{
private readonly ConcurrentDictionary<TKey, Lazy<TValue>> _cache = new();
private readonly Func<TKey, TValue> _factory;
public Memoizer(Func<TKey, TValue> factory) => _factory = factory;
public TValue Get(TKey key) =>
// GetOrAdd may run its argument MORE THAN ONCE under contention,
// so what races here is only the cheap Lazy allocation. Lazy itself
// guarantees _factory executes exactly once.
_cache.GetOrAdd(
key,
k => new Lazy<TValue>(
() => _factory(k),
System.Threading.LazyThreadSafetyMode.ExecutionAndPublication))
.Value;
}
// Usage:
// var memo = new Memoizer<string, byte[]>(LoadFromDisk);
// byte[] data = memo.Get("config.bin"); // LoadFromDisk runs onceThink 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 C#-specific trap
Performance in C#, beyond the O(1) cached
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Memoization?
ConcurrentDictionary<TKey, TValue>.GetOrAdd is the obvious tool and Lazy<T> is the one that makes it correct. System.Runtime.Caching.MemoryCache and Microsoft.Extensions.Caching.Memory add expiry and size limits when the memo table must be bounded.
What is the most common C# mistake when implementing Memoization?
ConcurrentDictionary.GetOrAdd does NOT guarantee the value factory runs only once. It is documented as being invoked outside the lock, so under contention several threads run it concurrently and all but one result is discarded. For a pure function that is merely wasted CPU; for a factory that opens a connection or calls a paid API it is a real defect, and it will not reproduce in single-threaded tests.
How does Memoization actually perform in C#?
The Lazy<T> wrapper costs one small allocation per key plus a volatile read on every subsequent hit, which is negligible against any factory worth memoizing. ConcurrentDictionary reads are lock-free entirely. Use LazyThreadSafetyMode.ExecutionAndPublication explicitly if you want the guarantee stated in the code rather than relying on the default. 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 trialIf you are a student, see what GitHub Copilot offers students for free 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.