Skip to content

Instantly share code, notes, and snippets.

@lorenzo
Created August 21, 2013 08:23
Show Gist options
  • Save lorenzo/6291721 to your computer and use it in GitHub Desktop.
Save lorenzo/6291721 to your computer and use it in GitHub Desktop.
This shows that calling a closure magically is faster than calling the margin method directly
<?php
/**
* Configuration options
*
*/
$iterations = 1000000;
info();
$callable = function() {
return 1 + 1;
};
/**
* Actual Benchmarks to run
*
*/
benchmark('direct-call', $iterations, function() use ($callable) {
$callable->__invoke();
});
benchmark('magic', $iterations, function() use ($callable) {
$callable();
});
// ----------------------------------------
// ----------------------------------------
// Modification below here not necessary,
// unless you're correcting some code that
// I fucked up.
// ----------------------------------------
// ----------------------------------------
/**
* Environment Information and Test Result header
*
* @return void
*/
function info() {
echo "/**\n";
echo " * ----------------------------------------\n";
echo " * PHP " . phpversion() . " (" . php_sapi_name() . ")\n";
echo " * Memory: " . (memory_get_peak_usage(true) / 1024 / 1024) . "MB / " . ini_get('memory_limit') . "\n";
echo " * ----------------------------------------\n";
echo " */\n\n";
}
/**
* Generic Benchmarking Function
*
* @param string $title Title of the test set
* @param string $iterations iterations to perform
* @param string $code Code to run
* @return void
*/
function benchmark($title, $iterations, $code) {
$start = microtime(true);
for ($i = 0; $i < $iterations; $i++) {
$code();
}
$elapsed = microtime(true) - $start;
echo "$title\n => $elapsed\n";
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment