1.2.90. 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.90.1. Suggestions

  • Avoid using blind variables outside loops.

  • Store blind variables in local variables or properties for later reuse.

1.2.90.2. Specs

Short name

Performances/CacheVariableOutsideLoop

Rulesets

All, Changed Behavior, Performances

Exakat since

1.2.8

PHP Version

All

Severity

Major

Time To Fix

Quick (30 mins)

Precision

Medium

Available in

Entreprise Edition, Exakat Cloud