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

时间:2022-05-09 07:46:36

I stumbled upon the question "Find the last element of an array while using a foreach loop in PHP" here at SO.

我偶然发现了问题“在PHP中使用foreach循环时查找数组的最后一个元素”。

In the comments user "johndodo" was claiming that there is no performance penalty for accessing count($array) each time in a foreach loop.

在评论中,用户“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. [...]"

“[...]在PHP中,每次访问计数($ arr)都没有性能损失。原因是项目计数在内部保存为数组头中的特殊字段,并且不是即时计算的。[ ...]”

So:

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

Should be equally as fast as:

应该同样快:

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

Well this is not the case. When doing profiling one can tell that a considerable amount of time is spent on doing count() in the first example. Is it because the claim laid forward by the user is moot or is it because we are calling a function in our tight foreach loop?

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

1 个解决方案

#1


1  

What "johndodo" was grasping at is that, as Mark Baker nicely pointed out in the comments, the array structure includes a count value internally, so it doesn't need to loop over the array counting each element every time.

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

What the statement by "johndodo" failed to consider is that calling a function has a large amount of overhead when called in a loop.

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

#1


1  

What "johndodo" was grasping at is that, as Mark Baker nicely pointed out in the comments, the array structure includes a count value internally, so it doesn't need to loop over the array counting each element every time.

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

What the statement by "johndodo" failed to consider is that calling a function has a large amount of overhead when called in a loop.

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