1.2.984. Pre-Calculate Use

In a closure <https://www.php.net/`closure>`_, it is faster to pass a final value, rather than calculate it at call time.

In the use clause of the closure <https://www.php.net/`closure>`_, make sure that the passed variables do not require any more processing, such as a call to another function or an extra expression.

This is a micro-optimisation. It has more potential with the closure <https://www.php.net/`closure>`_ used in a loop, or an array function.

<?php

// $b->get is calculated inside the closure
$d = $b->get();
$f = function ($a) use ($d) {
     return $d + $a;
}

// $b->get is calculated inside the closure
$f = function ($a) use ($b) {
     return $b->get() + $a;
}
?>

1.2.984.1. Suggestions

  • Inject the final value in the closure and avoid method calls inside the closure

1.2.984.2. Specs

Short name

Performances/PreCalculateUse

Rulesets

All, Changed Behavior, Performances

Exakat since

2.5.2

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

closure, micro-optimisation

Available in

Entreprise Edition, Exakat Cloud