Skip to content

ganglio/Memoizer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Memoizer

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);

About

PHP Memoizer class

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages