1.2.985. Pre-increment

When possible, use the pre-increment operator (++$i or --$i) instead of the post-increment operator ($i++ or $i--).

The latter needs an extra memory allocation that costs about 10% of performances. This is a micro-optimisation. However, its usage is so widespread, including within loops, that it may eventually have an significant impact on execution time. As such, it is recommended to adopt this rule, and only consider changing legacy code as they are refactored for other reasons.

<?php

// ++$i should be preferred over $i++, as current value is not important
for($i = 0; $i <10; ++$i) {
    // do Something
}

// ++$b and $b++ have different impact here, since $a will collect $b + 1 or $b, respectively.
$a = $b++;

?>

1.2.985.1. Suggestions

  • Use the pre increment when the new value is not reused.

1.2.985.2. Specs

Short name

Performances/PrePostIncrement

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior, Performances

Exakat since

0.8.4

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

Very high

Features

increment

Examples

ExpressionEngine, Traq

Available in

Entreprise Edition, Community Edition, Exakat Cloud