Memoization Implementation in Rust
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 Rust as in every other language.
- ✓No decorator and no stdlib memoize, because Rust has no way to attach state to a free function.
- ✓Own the cache in a struct and take &mut self. Use the entry API, map.entry(key).or_insert_with(closure), when the computation does not need to read the map, and split it into an explicit contains_key check plus insert when it does.
- ✓The Rust trap: or_insert_with(|| self.compute(k)) does not compile, and the error is one of the most confusing in the language: the entry call already borrowed self mutably, so the closure cannot borrow self again.
- ✓The entry API hashes the key exactly once for the lookup-and-insert, where a contains_key followed by insert hashes twice; on a hot path with expensive keys that is a real difference.
What Memoization actually is
Memoization in Rust: what you actually reach for
Rust implementation
use std::collections::HashMap;
use std::sync::OnceLock;
pub struct Fib {
memo: HashMap<u64, u64>,
}
impl Fib {
pub fn new() -> Self {
Self { memo: HashMap::new() }
}
pub fn get(&mut self, n: u64) -> u64 {
if let Some(&hit) = self.memo.get(&n) {
return hit;
}
// Compute into a LOCAL first: calling self.get inside
// entry().or_insert_with() would borrow self twice.
let value = if n < 2 { n } else { self.get(n - 1) + self.get(n - 2) };
self.memo.insert(n, value);
value
}
}
// Single lazily-computed value, thread-safe, no lock after init:
static TABLE: OnceLock<Vec<u32>> = OnceLock::new();
pub fn table() -> &'static Vec<u32> {
TABLE.get_or_init(|| (0..1024).map(|i| i * i).collect())
}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 Rust-specific trap
Performance in Rust, beyond the O(1) cached
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Memoization?
No decorator and no stdlib memoize, because Rust has no way to attach state to a free function. The idiomatic shape is a struct that owns a HashMap and exposes the memoized operation as a method. std::sync::OnceLock (stable since 1.70) memoizes a SINGLE value with thread safety and no locking after initialisation; the memoize and cached crates provide attribute macros for the general case.
What is the most common Rust mistake when implementing Memoization?
or_insert_with(|| self.compute(k)) does not compile, and the error is one of the most confusing in the language: the entry call already borrowed self mutably, so the closure cannot borrow self again. This bites hardest on recursive memoization, where the body legitimately needs the cache it is inserting into. The fix is to compute into a local first, then insert, restructuring, not fighting the checker.
How does Memoization actually perform in Rust?
The entry API hashes the key exactly once for the lookup-and-insert, where a contains_key followed by insert hashes twice; on a hot path with expensive keys that is a real difference. The default SipHash is DoS-resistant and comparatively slow, an internal memo table that never sees untrusted keys should use FxHashMap. Cloning owned keys to insert is often the largest hidden cost. 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 Replit 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.