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
?>
According to my benchmarking sizeof()
and count()
perform about the same, however to squeeze more performance out of the loop itself you can do the following:
for($i=0, $c=sizeof($unset);$i<$c;$i++){
$v=$v+1;
}
This should give it a performance boost because it doesn't have to evaluate with a function in each loop cycle.
The system I've used is here with the following code:
$b = new \Benchmark(10000);
$b->register('sizeof', function(){
$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;}
});
$b->register('count', function(){
$unset=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
for($i=0;$i<count($unset);$i++) {$v=$v+1;}
});
$b->register('count 2', function(){
$unset=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o');
for($i=0, $c=count($unset);$i<$c;$i++) {$v=$v+1;}
});
$b->register('preset', function(){
$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;}
});
print_r($b->start());
With this as the results:
Array
(
[stats] => Array
(
[phpversion] => 7.1.1
[itterations] => 40000
[duration] => 0.1180682182
[fastest] => preset
[slowest] => sizeof
)
[results] => Array
(
[0] => Array
(
[name] => preset
[time] => 0.0265829563
[average] => 0.0000026583
[speed] => 19.73%
)
[1] => Array
(
[name] => count 2
[time] => 0.0271441936
[average] => 0.0000027144
[speed] => 18.04%
)
[2] => Array
(
[name] => count
[time] => 0.0312242508
[average] => 0.0000031224
[speed] => 5.71%
)
[3] => Array
(
[name] => sizeof
[time] => 0.0331168175
[average] => 0.0000033117
[speed] => 0.00%
)
)
)