Back to results for “Functional Programming”
Node.js › Caching

What is memoization, and how does it differ from a general-purpose external cache like Redis?

Intermediate

Answer

Memoization caches the return value of a specific pure function based on its input arguments, entirely within the process's memory and scoped to that function -- a code-level optimization for avoiding redundant computation, whereas an external cache like Redis is a general-purpose, application-wide (and often multi-process) data store used for a much broader range of caching needs beyond a single function call.
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}
Real-world example A pricing-calculation function performing an expensive deterministic computation based on a product's attributes is wrapped in a memoization helper, speeding up repeated calls for the same product configuration within a single process.

Common follow-ups: Why is memoization only safe for pure, deterministic functions with no side effects?;What's the risk of memoizing a function whose input arguments are complex objects, given JSON.stringify-based key generation?