PHP 中 foreach和for循环哪个效率更高

今天看别人的代码,有段代码是对一个二维数组中的数据进行处理,那个作者用的是for循环,但是我感觉用 foreach 也可以。所以就想问问看在PHP中 for 循环和 foreach 哪个更快。

for循环遍历(count在内部):


    $big_Array = range(0,1000000,1);
    $start_For_Time = microtime_float();
    for ($i=0;$i<count($big_Array);$i++) {  
            $i;
    }
    $end_For_Time = microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo 'for循环遍历耗时:'.$for_Time.'<br>';  
    //for循环遍历(count在内部)耗时:0.039999961853027

for循环遍历(count在外部):

    $big_Array = range(0,1000000,1);
    $start_For_Time = microtime_float();
    $array_Count = count($big_Array);
    for ($i=0;$i<$array_Count;$i++) { 
          $i;
    }
    $end_For_Time = microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo 'for循环遍历耗时:'.$for_Time.'<br>';    
    //for循环遍历(count在外部)耗时:0.023999929428101

for循环 数组为固定长度:

    $start_For_Time = microtime_float();
    for ($i=0;$i<1000000;$i++) {  
            $i;
    }
    $end_For_Time = microtime_float();
    $for_Time = $end_For_Time - $start_For_Time;
    echo 'for循环遍历耗时:'.$for_Time.'<br>';   
    //for循环遍历(数组为固定长度)耗时:0.01200008392334

foreach循环遍历:

    $big_Array = range(0,1000000,1);
    $start_Foreach_Time = microtime_float();
    foreach ($big_Array as $key=>$val) {
            $key;
    }
    
    $end_Foreach_Time = microtime_float();
    $foreach_Time = $end_Foreach_Time - $start_Foreach_Time;
    echo 'foreach循环遍历耗时:'.$foreach_Time;   // foreach循环遍历耗时:0.019999980926514

时间计算:

/**
 *  时间统计函数
 */
private function microtime_float($time = null)
{
   list($usec, $sec) = explode(' ', $time ? $time : microtime());
   return ((float)$usec + (float)$sec);
}

从上面的测试中我们可以明显的得出两条结论:

1、在数组长度未知的情况下:

for(count在内部) < for(count在外部) < foreach(最快)

2、在数组长度已知的情况下:

 for循环比foreach更快

那么第二个问题:效率高的原因是什么呢?在寻找这个答案之前我们先探讨第三个问题,我们看一下原理分别是什么。

for循环:

每次从$i开始,每次循环都需要判断$i是否小于count,这占用了很大一部分时间
小于继续,否则终止循环

foreach遍历:

foreach 依赖 IEnumerable.
第一次 var a in GetList() 时 调用 GetEnumerator 返回第一个对象 并 赋给a,
以后每次再执行 var a in GetList() 的时候 调用 MoveNext.直到循环结束.
期间GetList()方法只执行一次.


原文:https://blog.csdn.net/bianb123/article/details/80418989 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值