ganglio/memoizer

Simple PHP Memoizer class

v1.0.4.2 2016-03-02 11:15 UTC

This package is not auto-updated.

Last update: 2024-05-11 16:23:50 UTC


README

Simple PHP Memoizer class

Latest Stable Version Build Status codecov.io Code Climate Scrutinizer Code Quality License

The class allow to encapsulate any callable so that, during the first call (with a given set of arguments), the callable is executed and the return values are stored. At every successive call (with the same set of arguments) the stored value is used instead of invoking the callable again.

Examples

This is a dumb example with a time variant call just to demonstate the way the memoized function works. If your callable has that kind of behaviour memoizing it is probably not a good idea :D

$myFunc = function ($a) {
	return $a * mt_rand();
}

$myMemoizedFunc = new Memoizer($myFunc);

echo "Returns: " . $myMemoizedFunc(3) . "\n";
echo "Returns the same value: " . $myMemoizedFunc(3) . "\n";

A time consuming callable can be made more efficient storing the return value for later invokation.

$mySlowFunc = function ($a) {
	sleep(5);
	return $a * mt_rand();
}

$myMemoizedSlowFunc = new Memoizer($mySlowFunc);

$st = time();
echo "Returns: " . $myMemoizedSlowFunc(3) . " in: " . (time() - $st);

$st = time();
echo "Returns the same value: " . $myMemoizedSlowFunc(3) . " in basically 0 time: " . (time() - $st);