Gyaan

Memoization

intermediate performance optimization caching

Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

In simple language, if a function is called with the same arguments again, return the stored result instead of computing it again.

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      console.log("Returning from cache");
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

const expensiveAdd = (a, b) => {
  console.log("Computing...");
  return a + b;
};

const memoizedAdd = memoize(expensiveAdd);

memoizedAdd(1, 2); // "Computing..." → 3
memoizedAdd(1, 2); // "Returning from cache" → 3
memoizedAdd(3, 4); // "Computing..." → 7

Memoization works best with functions that always give the same output for the same input (these are called pure functions). It is commonly used in recursive functions like fibonacci, caching API responses, and heavy calculations in UI rendering.