加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 为什么反循环比正常循环更快(包括测试)

发布时间:2020-12-13 17:03:04 所属栏目:PHP教程 来源:网络整理
导读:我在 PHP循环中运行了一些小测试.我不知道我的方法是否合适. 我发现反向循环比正常循环快. 我还发现while循环比for循环更快. Setup ?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;
我在 PHP循环中运行了一些小测试.我不知道我的方法是否合适.

我发现反向循环比正常循环快.

我还发现while循环比for循环更快.

Setup

<?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>";
?>

Average Results

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

Questions

我的问题是有人可以解释这些结果的差异吗?
我的基准测试方法是否正确?

解决方法

使用inverse for循环,每次迭代只进行一次变量查找:

$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

当然,你在循环的代码块中有额外的操作,但我不确定为什么它更快(也许有人可以在那里填空).您会注意到时差是最小的,因为这些操作仍然非常快.这种微优化在非常大的循环上最有效.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读