Created
March 20, 2012 19:04
-
-
Save kurtpayne/2139883 to your computer and use it in GitHub Desktop.
PHP Memoization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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