PHP

Memoize a Function's Result

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cache the result of an expensive pure function by its arguments. Returns a closure with the same call signature that only invokes the inner function once per unique argument set.
PHP
Raw
<?php
function memoize(callable $fn): callable {
    $cache = [];
    return function (...$args) use ($fn, &$cache) {
        $key = md5(serialize($args));
        if (!array_key_exists($key, $cache)) {
            $cache[$key] = $fn(...$args);
        }
        return $cache[$key];
    };
}

$slowSqrt = memoize(function (int $n) {
    sleep(1);              // imagine an expensive computation
    return sqrt($n);
});

echo $slowSqrt(9);   // 3 — first call takes 1 second
echo $slowSqrt(9);   // 3 — instant on subsequent calls
echo $slowSqrt(16);  // 4 — first call for this arg
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.