Glossary

Memoization

Memoization is an optimisation where the results of expensive function calls are cached by their arguments and returned without recomputation on the same input. A specialised form of caching where the cache key is the function's arguments.

Example

function memoize(callable $fn): Closure {
  $cache = [];
  return function() use ($fn, &$cache) {
    $key = serialize(func_get_args());
    if (!isset($cache[$key])) {
      $cache[$key] = $fn(...func_get_args());
    }
    return $cache[$key];
  };
}

$fib = memoize(function(int $n) use (&$fib): int {
  return $n <= 1 ? $n : $fib($n-1) + $fib($n-2);
});

$fib(40); // O(n) instead of O(2^n)

When to apply