Skip to content

Instantly share code, notes, and snippets.

@bartosz-maciaszek
Created September 29, 2014 18:11
Show Gist options
  • Save bartosz-maciaszek/abcd2ac4fea3de4f385c to your computer and use it in GitHub Desktop.
Save bartosz-maciaszek/abcd2ac4fea3de4f385c to your computer and use it in GitHub Desktop.
Direct call vs call_user_func() vs call_user_func_array()
<?php
class Benchmark
{
private $start = null;
public function __construct()
{
$this->start = microtime(true);
}
public function stop()
{
return microtime(true) - $this->start;
}
}
$benchmarkFunction = function() {
return array_sum(func_get_args());
};
$repeat = function($times, Closure $c) {
for ($i = 0; $i < $times; $i++) {
$c();
}
};
$b = new Benchmark();
$repeat(1000000, function() use ($benchmarkFunction) {
$benchmarkFunction(1, 2, 3, 4, 5);
});
echo "direct: " . $b->stop() . PHP_EOL;
$b = new Benchmark();
$repeat(1000000, function() use ($benchmarkFunction) {
call_user_func($benchmarkFunction, 1, 2, 3, 4, 5);
});
echo "call_user_func: " . $b->stop() . PHP_EOL;
$b = new Benchmark();
$repeat(1000000, function() use ($benchmarkFunction) {
call_user_func_array($benchmarkFunction, [1, 2, 3, 4, 5]);
});
echo "call_user_func_array: " . $b->stop() . PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment