我也想知道在檢查類別方法時,is_callable 或 function_exists 哪個速度更快。因此,我設定了以下測試
<?php
function doTimes($start, $end)
{
$start_time = explode (" ", $start);
$start_time = $start_time[1] + $start_time[0];
$end_time = explode (" ", $end);
$end_time = $end_time[1] + $end_time[0];
$time = $end_time - $start_time;
return $time;
}
class test
{
function test()
{
return true;
}
}
$callableIsTrue = false;
$startIsCallable = microtime();
for($i = 0; $i < 10000; $i++)
{
if(is_callable(array('test', 'test'))) { $callableIsTrue = true; }
}
$endIsCallable = microtime();
$existsIsTrue = false;
$startExists = microtime();
for($i = 0; $i < 10000; $i++)
{
if(function_exists('test::test')) { $existsIsTrue = true; }
}
$endExists = microtime();
$timeIsCallable = doTimes($startIsCallable, $endIsCallable);
$timeExists = doTimes($startExists, $endExists);
echo "<b>is_callable = ".($callableIsTrue ? "TRUE" : "FALSE")."</b>, \n";
echo "<b>function_exists = ".($existsIsTrue ? "TRUE" : "FALSE")."</b><br>\n";
echo "<br>Did 10000 is_callables in ".$timeIsCallable." seconds";
echo "<br>Did 10000 function_exists in ".$timeExists." seconds";
?>
輸出結果如下
is_callable = TRUE, function_exists = FALSE
執行 10000 次 is_callables 花費 0.0640790462494 秒
執行 10000 次 function_exists 花費 0.0304429531097 秒
因此,function_exists 速度快兩倍的事實,稍微被它不適用於類別方法的事實所掩蓋,至少就我所知是這樣。