Oihana PHP

memoizeCallable.php

Table of Contents

Functions

memoizeCallable()  : callable
Memoizes a callable's result (caches based on arguments).

Functions

memoizeCallable()

Memoizes a callable's result (caches based on arguments).

memoizeCallable(callable $callable) : callable

Returns a new callable that caches results based on the arguments passed. Subsequent calls with the same arguments return the cached result instead of re-executing the original callable. This improves performance for expensive computations with repeated identical arguments.

Cache keys are generated by serializing arguments using serialize(). Works with scalar values, arrays, and objects that support serialization.

WARNING: The cache grows indefinitely. For long-running processes with many unique argument combinations, consider clearing the cache or using a size limit.

Parameters
$callable : callable

The original callable to memoize

Tags
example
use function oihana\core\callables\memoizeCallable;

// Example 1: Expensive computation
$expensive = function($n) {
    echo "Computing...";
    return $n * $n;
};

$memoized = memoizeCallable($expensive);
echo $memoized(5); // "Computing..." outputs 25
echo $memoized(5); // outputs 25 (cached, no "Computing...")
echo $memoized(6); // "Computing..." outputs 36 (different arg)

// Example 2: API call memoization
$fetchUser = memoizeCallable( function( $userId )
{
    return file_get_contents("https://api.example.com/users/{$userId}");
} ) ;

$user1 = $fetchUser(123); // Makes actual API call
$user2 = $fetchUser(123); // Returns cached result

// Example 3: Fibonacci with memoization
$fib = null;
$fib = memoizeCallable( function($n) use (&$fib)
{
    if ($n <= 1) return $n;
    return $fib($n - 1) + $fib($n - 2);
});
echo $fib(30); // Very fast due to memoization

// Example 4: With multiple arguments
$add = memoizeCallable(fn($a, $b) => $a + $b);
echo $add( 2 , 3 ) ; // 5
echo $add( 2 , 3 ) ; // 5 (cached)
echo $add( 3 , 2 ) ; // 5 (different cache key since args differ)
see
wrapCallable()

To apply custom decorators instead

author

Marc Alcaraz (ekameleon)

since
1.0.7
Return values
callable

A new callable with memoization enabled


        
On this page

Search results