Skip to content

Instantly share code, notes, and snippets.

@kurtpayne
Created March 20, 2012 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kurtpayne/2139883 to your computer and use it in GitHub Desktop.
Save kurtpayne/2139883 to your computer and use it in GitHub Desktop.
PHP Memoization
<?php
function args_to_key($args) {
$tmp = array();
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($args));
foreach($it as $v) {
if (is_object($v)) {
$tmp[] = spl_object_hash($v);
} elseif (is_scalar($v)) {
$tmp[] = $v;
}
}
return md5(implode('', $tmp));
}
function __memoize($func) {
$_func = function() use ($func) {
static $cache = array();
$args = func_get_args();
$key = args_to_key($args);
if (array_key_exists($key, $cache)) {
return $cache[$key];
}
$ret = call_user_func_array($func, $args);
$cache[$key] = $ret;
return $cache[$key];
};
return $_func;
}
function slow($a, $b) {
sleep(1);
return mt_rand(1, 1000);
}
echo "Calling slow(1, 2): ";
$start = microtime(true);
echo slow(1, 2) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "Calling slow(1, 2): ";
$start = microtime(true);
echo slow(1, 2) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "\n\nMemoizing it\n\n";
$slow = __memoize('slow');
echo "Calling slow(1, 2): ";
$start = microtime(true);
echo $slow(1, 2) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "Calling slow(1, 2): ";
$start = microtime(true);
echo $slow(1, 2) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "Calling slow(3, 4): ";
$start = microtime(true);
echo $slow(3, 4) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "Calling slow(3, 4): ";
$start = microtime(true);
echo $slow(3, 4) . "\n";
printf("Took: %.4f seconds\n", microtime(true) - $start);
echo "\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment