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?