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

php – 每次在foreach循环中访问count($array)会有性能损失吗?

发布时间:2020-12-13 22:51:27 所属栏目:PHP教程 来源:网络整理
导读:我偶然发现了问题“ Find the last element of an array while using a foreach loop in PHP”. 在comments用户中,“johndodo”声称每次在foreach循环中访问count($array)都没有性能损失. “[…] in PHP there is no performance penalty for accessing coun
我偶然发现了问题“ Find the last element of an array while using a foreach loop in PHP”.

在comments用户中,“johndodo”声称每次在foreach循环中访问count($array)都没有性能损失.

“[…] in PHP there is no performance penalty for accessing count($arr) each time. The reason is that items count is internally saved as special field in the array header and is not calculated on-the-fly. […]”

所以:

foreach ($array as $line) {
    $output .= '    ' . $line;
    // add LF if not the last line
    if ($array[count($array) - 1] != $line) {
        $output .= "n";
    }
}

应该同样快:

$arrayLen = count($array) - 1;
foreach ($array as $line) {
    $output .= '    ' . $line;
    // add LF if not the last line
    if ($array[$arrayLen] != $line) {
        $output .= "n";
    }
}

那不是这样的.在进行性能分析时,可以判断在第一个示例中花费了大量时间来执行count().是因为用户提出的主张是没有意义的,还是因为我们在紧张的foreach循环中调用了一个函数?

解决方法

“johndodo”正在抓住的是,正如Mark Ba??ker在评论中很好地指出的那样,数组结构在内部包含一个计数值,因此它不需要遍历每次计算每个元素的数组.

“johndodo”的陈述未能考虑的是调用函数在循环中调用时会产生大量开销.

(编辑:李大同)

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

    推荐文章
      热点阅读