I'm confused about the speed of the sizeof($x) vs $x when in a loop. This site: phpbench.com claims that the loop of sizeof($x) without pre calc -count() is THOUSANDS of percent slower than with pre calc count(). So I did a test as below, but I'm not sure if this is the right way to test it. The results show that the time is almost the same for each function. So I don't understand how it would be so much different from the phpbench website.
In summary, I'd like to know a definite answer if function a (with sizeof($unset)) is really considerably slower than function b (with pre calculated $unset value). I think now the values/functions are stored in memory so sizeof($x) could actually be faster than on servers from several years ago?
<?php
$v=0;
function a()
{
//sizeof
$unset=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
for($i=0;$i<sizeof($unset);$i++) {$v=$v+1;}
return;
}
function b()
{
//pre calculated
$unset=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
for($i=0;$i<15;$i++) {$v=$v+1;}
return;
}
function benchmark($func)
{
$start = microtime(true);
for ($i = 0; $i < 500000; $i++) {
$func();
}
$end = microtime(true);
$time = $end - $start;
echo $func . " time: " . sprintf('%.4f', $time) . PHP_EOL.'<br>';
}
benchmark('a'); // sizeof
benchmark('b'); // count
?>