php 38 lines · 8 steps

How memoization works in PHP closures

A higher-order function caches any callable's results by its arguments using a closure that captures state by reference.

Explained by highlit
1function memoize(callable $fn): callable
2{
3 $cache = [];
4 
5 return function (...$args) use (&$cache, $fn) {
6 $key = md5(serialize($args));
7 
8 if (array_key_exists($key, $cache)) {
9 return $cache[$key];
10 }
11 
12 return $cache[$key] = $fn(...$args);
13 };
14}
15 
16$fibonacci = memoize(function (int $n) use (&$fibonacci): int {
17 return $n < 2 ? $n : $fibonacci($n - 1) + $fibonacci($n - 2);
18});
19 
20$primeFactors = memoize(function (int $number): array {
21 $factors = [];
22 $divisor = 2;
23 
24 while ($number > 1) {
25 while ($number % $divisor === 0) {
26 $factors[] = $divisor;
27 $number = intdiv($number, $divisor);
28 }
29 $divisor++;
30 
31 if ($divisor * $divisor > $number && $number > 1) {
32 $factors[] = $number;
33 break;
34 }
35 }
36 
37 return $factors;
38});
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Capturing a variable by reference lets a closure keep mutable state alive across many calls.
  2. 2Serializing and hashing arguments gives a stable cache key for arbitrary input shapes.
  3. 3Recursive functions gain the biggest speedup from memoization because each subproblem is solved once.

Related explainers

Share this explainer

Here's the card — post it anywhere.

How memoization works in PHP closures — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code