我对 PHP 进行了以下性能测试。我正在尝试以四种方式在数组中分析增加变量所需的时间$time: [{++$x}, {$x++}, {$x += 1}, {$x = $x + 1}]
$time = [0, 0, 0, 0];
for($i = 0; $i < 50; ++$i){
$k = 0;
$t = microtime(true);
$x = 0;
for($j = 0; $j < 100; ++$j)
++$x;
$time[$k++] += microtime(true) - $t;
$t = microtime(true);
$x = 0;
for($j = 0; $j < 100; ++$j)
$x++;
$time[$k++] += microtime(true) - $t;
$t = microtime(true);
$x = 0;
for($j = 0; $j < 100; ++$j)
$x += 1;
$time[$k++] += microtime(true) - $t;
$t = microtime(true);
$x = 0;
for($j = 0; $j < 100; ++$j)
$x = $x + 1;
$time[$k++] += microtime(true) - $t;
}
echo '++$x: ', $time[0] * 1000, 'ms<br />';
echo '$x++: ', $time[1] * 1000, 'ms<br />';
echo '$x += 1: ', $time[2] * 1000, 'ms<br />';
echo '$x = $x + 1: ', $time[3] * 1000, 'ms<br />';
我平均跑了 10 次:0.28ms for ++$x and $x++, 0.26ms for $x += 1 and 0.24ms for $x = $x + 1
我想,++$x 和 $x++ 更快,但在这里它们更慢。我的脚本是否出错,或者这真的是 PHP 5.5.9 的正常性能吗?