PHP code example of loophp / memoize
1. Go to this page and download the library: Download loophp/memoize library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
loophp / memoize example snippets
declare(strict_types=1);
namespace App;
Memoizer;
$fibonacci = static function (int $number) use (&$fibonacci): int {
return (1 >= $number) ?
$number :
$fibonacci($number - 1) + $fibonacci($number - 2);
};
$fibonacciMemoized = static function (int $number) use (&$fibonacciMemoized): int {
return (1 >= $number) ?
$number :
$fibonacciMemoized($number - 1) + $fibonacciMemoized($number - 2);
};
$fibonacciMemoized = Memoizer::fromClosure($fibonacciMemoized);
function bench(Closure $closure, ...$arguments): array
{
$eval = static function (Closure $closure, ...$arguments): Generator {
yield microtime(true);
yield $closure(...$arguments);
yield microtime(true);
};
$result = iterator_to_array($eval($closure, ...$arguments));
return [
$result[1],
$result[2] - $result[0],
];
}
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacci, 30))); // ~3 seconds
var_dump(sprintf('[return: %s] [duration: %s]', ...bench($fibonacciMemoized, 30))); // ~0.0003 seconds