我在一个循环中对sizeof($ x)vs $ x的速度感到困惑。这个网站:phpbench.com声称没有pre calc -count()的sizeof($ x)循环比
总之,如果函数a(sizeof($ unset))实际上比函数b慢得多(使用预先计算的$ unset值),我想知道一个明确的答案。我认为现在值/函数存储在内存中,因此sizeof($ x)实际上比几年前的服务器更快?
<?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
?>
答案 0 :(得分:1)
根据我的基准sizeof()
和count()
执行相同的操作,但是为了从循环中挤出更多性能,您可以执行以下操作:
for($i=0, $c=sizeof($unset);$i<$c;$i++){
$v=$v+1;
}
这应该会提高性能,因为它不必在每个循环周期中使用函数进行求值。
我使用的系统是here,代码如下:
$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());
结果如下:
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%
)
)
)