Caching and Memoization for Repeated Work
You'll learn how to save computed results so expensive operations only run once, making subsequent calls nearly instant.
The Core Idea
Imagine calculating a complicated math problem — once you've solved it, you write down the answer. If someone asks the same question again, you just read your note instead of recalculating. That's exactly what caching and memoization do in code: they store results from expensive operations and return the cached value when the same input appears again.
How It Works
Caching is the general concept of storing data for reuse. Memoization is a specific form where you cache function results based on their arguments.
Here's a simple memoization example:
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (key in cache) {
return cache[key]; // Instant lookup!
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
function expensiveCalculation(n) {
// Pretend this takes a long time
let sum = 0;
for (let i = 0; i < n * 1000000; i++) {
sum += i;
}
return sum;
}
const memoized = memoize(expensiveCalculation);
memoized(5); // Slow first time
memoized(5); // Instant! Returns cached result
memoized(10); // Slow (new input)
memoized(5); // Still instant!
The first call with any input does the work and stores the result. Every subsequent call with that same input skips the calculation entirely and returns the stored answer.
This technique shines when you have expensive operations (complex calculations, API calls, recursive functions) that get called repeatedly with the same inputs.
Key Takeaway: Memoization turns expensive recalculations into cheap object lookups by remembering results — if you've seen the input before, return the cached answer instead of doing the work again.