Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Memoization is a technique where you cache the results of expensive function calls and return the cached result when the same inputs occur again. Perfect for optimization!
Click Start to see how memoization caches function results
Cache is empty
Function Calls
0
Cache Hits
0
Cache Size
0
// Slow - recalculates every time
function expensiveOperation(n) {
console.log('Computing for', n);
let result = 0;
for (let i = 0; i < n * 1000000; i++) {
result += i;
}
return result;
}
expensiveOperation(5); // Computes
expensiveOperation(5); // Computes AGAIN!
expensiveOperation(5); // Still computing!// Fast - cache results
const cache = {};
function expensiveOperation(n) {
if (n in cache) {
console.log('Cache hit for', n);
return cache[n];
}
console.log('Computing for', n);
let result = 0;
for (let i = 0; i < n * 1000000; i++) {
result += i;
}
cache[n] = result;
return result;
}
expensiveOperation(5); // Computes once
expensiveOperation(5); // Cache hit! ⚡
expensiveOperation(5); // Cache hit! ⚡Reusable memoization wrapper
// Least Recently Used cache
function memoizeWithLimit(fn, limit = 100) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
// Move to end (mark as recently used)
const value = cache.get(key);
cache.delete(key);
cache.set(key, value);
return value;
}
const result = fn.apply(this, args);
// Remove oldest if at limit
if (cache.size >= limit) {
const firstKey = cache.keys().next().value;
cache.delete(firstKey);
}
cache.set(key, result);
return result;
};
}
// With Time-To-Live (TTL)
function memoizeWithTTL(fn, ttl = 5000) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
const cached = cache.get(key);
if (cached && Date.now() - cached.timestamp < ttl) {
console.log('Valid cache hit');
return cached.value;
}
const result = fn.apply(this, args);
cache.set(key, {
value: result,
timestamp: Date.now()
});
return result;
};
}
// Usage
const fetchUser = memoizeWithTTL(async (id) => {
const response = await fetch(`/api/users/${id}`);
return response.json();
}, 5000); // Cache for 5 seconds
await fetchUser(1); // API call
await fetchUser(1); // Cached (within 5s)
// After 5 seconds...
await fetchUser(1); // Fresh API callBest practices and gotchas
Memoization in React with useMemo (simulated)
Store expensive computation results
Return cached value for same inputs
Dramatic speedup for recursive functions
Avoid redundant calculations
Works with deterministic functions
No side effects allowed
Uses memory for cache
Add size limits and TTL when needed