脚本宝典收集整理的这篇文章主要介绍了php – 为什么反循环比正常循环更快(包括测试),脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我发现反向循环比正常循环快.
我还发现while循环比for循环更快.
<?PHP $counter = 10000000; $w=0;$x=0;$y=0;$z=0; $wstart=0;$xstart=0;$ystart=0;$zstart=0; $wend=0;$Xend=0;$yend=0;$zend=0; $wstart = microtime(true); for($w=0; $w<$counter; $w++){ echo ''; } $wend = microtime(true); echo "normal for: " . ($wend - $wstart) . "<br />"; $xstart = microtime(true); for($x=$counter; $x>0; $x--){ echo ''; } $xend = microtime(true); echo "inverse for: " . ($xend - $xstart) . "<br />"; echo "<hr> normal - inverse: " . (($wend - $wstart) - ($xend - $xstart)) . "<hr>"; $ystart = microtime(true); $y=0; while($y<$counter){ echo ''; $y++; } $yend = microtime(true); echo "normal while: " . ($yend - $ystart) . "<br />"; $zstart = microtime(true); $z=$counter; while($z>0){ echo ''; $z--; } $zend = microtime(true); echo "inverse while: " . ($zend - $zstart) . "<br />"; echo "<hr> normal - inverse: " . (($yend - $ystart) - ($zend - $zstart)) . "<hr>"; echo "<hr> inverse for - inverse while: " . (($xend - $xstart) - ($zend - $zstart)) . "<hr>"; ?>
for循环的区别
normal for:1.0908501148224
逆:1.0212800502777
normal – inverse:0.069570064544678
while循环的区别
正常的同时:1.0395669937134
逆时间:0.99321985244751
normal – inverse:0.046347141265869
for循环和while循环的区别
inverse for – inverse while:0.0280601978302
我的问题是有人可以解释这些结果的差异吗?
我的基准测试方法是否正确?
$w > 0 // <-- one lookup to the $w VARiable $w < $counter // <-- two lookups,one for $w,one for $counter
这就是反转稍快的原因.此外,while循环每次迭代只有一个操作:
$w < $counter // <-- one operation while loop $w < $counter ; $w++ // <-- two oPEration for loop
当然,你在循环的代码块中有额外的操作,但我不确定为什么它更快(也许有人可以在那里填空).您会注意到时差是最小的,因为这些操作仍然非常快.这种微优化在非常大的循环上最有效.
以上是脚本宝典为你收集整理的php – 为什么反循环比正常循环更快(包括测试)全部内容,希望文章能够帮你解决php – 为什么反循环比正常循环更快(包括测试)所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。