What is Memoization in JavaScript: Simple Explanation and Example
memoization is a technique to speed up functions by saving the results of expensive calls and returning the cached result when the same inputs occur again. It helps avoid repeating the same work, making your code faster and more efficient.How It Works
Memoization works like a smart notebook that remembers answers to questions you've already asked. Imagine you ask a friend to solve a math problem. The first time, they take time to solve it, but they write down the answer. Next time you ask the same problem, they just look at their notes and give you the answer immediately.
In JavaScript, memoization stores the results of function calls in a cache object. When the function is called again with the same inputs, it checks the cache first. If the answer is there, it returns it right away without doing the work again. This saves time especially for functions that take a long time to compute.
Example
This example shows a simple memoized function to calculate Fibonacci numbers. Without memoization, the function does a lot of repeated work. With memoization, it remembers results and runs much faster.
function memoizedFibonacci() { const cache = {}; function fib(n) { if (n <= 1) return n; if (cache[n] !== undefined) return cache[n]; cache[n] = fib(n - 1) + fib(n - 2); return cache[n]; } return fib; } const fib = memoizedFibonacci(); console.log(fib(10));
When to Use
Use memoization when you have functions that do heavy or repeated calculations with the same inputs. It is especially useful in cases like:
- Calculating Fibonacci numbers or factorials
- Processing data where inputs repeat often
- Optimizing recursive functions
Memoization helps improve performance by avoiding unnecessary work, making your app faster and more responsive.
Key Points
- Memoization caches function results to speed up repeated calls.
- It works best for pure functions with the same output for the same input.
- Helps optimize expensive or recursive calculations.
- Uses extra memory to store cached results.