📎 Webclip
Memoization in JavaScript
The article explains memoization as a way to avoid repeating expensive calculations when a function receives the same inputs again. It uses a slow multiplication example to show that the second call can reuse a cached result instead of running the function body again.
Reading notes#
- Memoization returns a cached output when the same inputs are used again.
- The example wraps
slowProduct()inmyMemoize()and stores the memoized function inmemoizedProduct. myMemoize()keeps results in an object keyed byJSON.stringify(args).- When a key is missing, it calls the original function, stores the result, and returns it.
- The complete example shows the second call reusing the stored value instead of recalculating.
- A later change lets
myMemoize()accept an optional context and usesfn.call(context || this, ...args). - The conclusion says memoization can improve performance and can be combined with other optimizations.
