Memoization In PHP: Caching Method Results

Memoization is an optimization pattern, which involves caching results that a function returns. Any subsequent calls to function to calculate same computation will instead retrieve from the result cache. This avoids wasting valuable computer resources by not repeating the same calculation.

This first method caches single parameter method calls.


class Util {

	function expCalc($param) {

                static $cache;

		if(!$cache[$param]) {

			$result = 'expensive calculation';

                        $cache[$param] = $result;
		}

		return $cache[$param];

	}

}

This method will add the result to cache as an array hash value for each different parameter value passed to it. The cache variable is static so it maintains its value for each method call.

You can call the method statically or as an instance method.


$val = Util::expCalc(1);

This second method shows how to handle multiple parameters in the method call.


class Util {

	function expCalc($param1,$param2,$param3) {
		static $cache;

		$key = json_encode(func_get_args());

		if(!$cache[$key]) {

			$result = 'expensive calculation';

			$cache[$key] = $result;
		}

		return $cache[$key];

	}

}

The only difference in this method and previous is the way the cache array key is generated. This will get all the arguments passed to method as an array and turn it into a JSON formatted string as the array key. Arguments can be any combination of strings, integers, arrays and objects. The serialize() function can also be used to make the key but json_encode() makes a more compact key. You will need at least PHP 5.2+ to use the JSON functions.

Leave a comment

0 Comments.

Leave a Reply


[ Ctrl + Enter ]