Created
October 28, 2010 22:35
-
-
Save stuartloxton/652483 to your computer and use it in GitHub Desktop.
Closure Memoization in PHP
This file contains hidden or 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 Memoize($function) { | |
$cache = array(); | |
return function() use (&$cache, $function) { | |
$args = func_get_args(); | |
$serialized = serialize($args); | |
if( isset($cache[$serialized]) ) | |
return $cache[$serialized]; | |
$val = call_user_func_array($function, $args); | |
$cache[$serialized] = $val; | |
return $val; | |
}; | |
} | |
function Benchmark($name, $runs, $function) { | |
$start = microtime(true); | |
while( $runs-- ) { | |
$function(); | |
} | |
$end = microtime(true); | |
echo $name.": ".($end - $start)."\n"; | |
} | |
$fib = function($n) use (&$fib) { | |
if( $n < 3 ) | |
return 1; | |
else | |
return $fib($n - 1) + $fib($n - 2); | |
}; | |
Benchmark('$fib(15)', 900, function() use ($fib) { | |
for( $i = 0; $i < 20; $i++ ) { | |
$fib($i); | |
} | |
}); | |
$fib = Memoize($fib); | |
Benchmark('Memoized $fib(15)', 900, function() use ($fib) { | |
for( $i = 0; $i < 20; $i++ ) { | |
$fib($i); | |
} | |
}); | |
/******************** | |
* $fib(15): 6.2607789039612 | |
* Memoized $fib(15): 0.032751083374023 | |
********************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment