代码之家  ›  专栏  ›  技术社区  ›  Saif Bechan

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

  •  4
  • Saif Bechan  · 技术社区  · 16 年前

    我已经用PHP在循环上运行了一些小测试。我不知道我的方法是否好。

    我发现逆循环比正常循环快。

    安装程序

    <?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循环中的差异

    正常值:1.0908501148224
    反向:1.021280052777

    while循环中的差异


    反时限:0.99321985244751

    for循环和while循环的区别

    问题

    我的问题是有人能解释这些结果上的差异吗?

    1 回复  |  直到 16 年前
        1
  •  4
  •   Andy E    16 年前

    对于逆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
    

    推荐文章