<?php
version_compare(PHP_VERSION, '7.1', '>=') || die;
class MyClass
{
public static function callStatic($arg, $i)
{
return sprintf("%s %d\n", $arg, $i);
}
public function callable($arg, $i)
{
return sprintf("%s %d\n", $arg, $i);
}
public static function getCallable()
{
return [new static(), 'callable'];
}
public static function getClosure()
{
return Closure::fromCallable([new static(), 'callable']);
}
}
function callFunc($arg, $i)
{
return sprintf("%s %d\n", $arg, $i);
}
$nTests = 100000;
$result = 0;
foreach([
'callable' => MyClass::getCallable(),
'closure ' => MyClass::getClosure(),
'callstat' => ['MyClass', 'callStatic'],
'csclosed' => Closure::fromCallable(['MyClass', 'callStatic']),
'function' => 'callFunc',
'fnclosed' => Closure::fromCallable('callFunc'),
] as $name => $function)
{
ob_start();
$_start = microtime(true);
for($i = 0; $i < $nTests; $i++)
{
$function('callable', $i);
}
$_end = microtime(true);
ob_end_clean();
$_runtime = $_end - $_start;
printf("%s in %.4f sec, %5.1f\n", $name, $_runtime, ($result & 1) * 100 * ($_runtime / ($_old ?? $_runtime)));
$_old = $_runtime;
$result++;
}
preferences:
33.51 ms | 402 KiB | 5 Q