Counter Functions In Loops
ID |
php.counter_functions_in_loops |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Php |
Tags |
efficiency, performance |
Description
Reports a call to a size-counting function such as count() or sizeof() inside the
condition of a for or while loop. The condition is evaluated before every iteration, so
the count is recomputed on each pass instead of once.
Rationale
A loop condition runs on every iteration. Calling count($items) there asks PHP to size the
same array again and again, adding a per-iteration cost that grows with the number of passes.
For a loop that already walks the collection, this effectively doubles the work. Computing the
size once, before the loop, and comparing against the cached value removes the repeated calls
without changing behaviour.
<?php
function sum(array $items): int
{
$total = 0;
for ($i = 0; $i < count($items); $i++) { // FLAW - count() runs on every iteration
$total += $items[$i];
}
$n = count($items); // OK - size computed once
for ($i = 0; $i < $n; $i++) {
$total += $items[$i];
}
return $total;
}
Remediation
Compute the size once into a local variable before the loop and compare against that variable in the condition. When the collection can change inside the loop, recompute the cached size explicitly at the point it changes rather than on every iteration.