1.2.91. Cache Variable Outside Loop¶
Avoid recalculating constant values inside the loop.
Do the calculation once, outside the loop, and then reuse the value in the body of the loop.
One of the classic example if doing count($array)
in a for
loop : since the source is constant during the loop, the result of count() is always the same.
Depending on the load of the called method, this may increase the speed of the loop from little to enormously.
This analysis works on all the loops: while, do…while, foreach and for.
<?php
$path = '/some/path';
$fullpath = realpath("$path/more/dirs/");
foreach($files as $file) {
// Only moving parts are used in the loop
copy($file, $fullpath.$file);
}
$path = '/some/path';
foreach($files as $file) {
// $fullpath is calculated each loop
$fullpath = realpath("$path/more/dirs/");
copy($file, $fullpath.$file);
}
?>
1.2.91.1. Connex PHP features¶
1.2.91.1.1. Suggestions¶
Store non-blind variables in local variables or properties before the loop.
1.2.91.1.2. Specs¶
Short name |
Performances/CacheVariableOutsideLoop |
Rulesets |
|
Exakat since |
1.2.8 |
PHP Version |
All |
Severity |
Major |
Time To Fix |
Quick (30 mins) |
Precision |
Medium |
Available in |