user555
user555

Reputation: 1554

Is there a performance penalty for accessing count($array) each time in a foreach loop?

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

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

"[...] 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. [...]"

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?

Upvotes: 4

Views: 1565

Answers (1)

user555
user555

Reputation: 1554

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.

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

Upvotes: 2

Related Questions