1.2.61. Avoid Concat In Loop

Concatenations inside a loop generate a lot of temporary variables. They are accumulated and tend to raise the memory usage, leading to slower performances.

It is recommended to store the values in an array, and then use implode() on that array to make the concatenation at once. The effect is positive when the source array has at least 50 elements. The same doesn’t apply to addition and multiplication, with array_sum() and array_multiply(), as those operations work on the current memory allocation, and don’t need to allocate new memory at each step.

<?php

// Concatenation in one operation
$tmp = array();
foreach(data_source() as $data) {
    $tmp[] = $data;
}
$final = implode('', $tmp);

// Concatenation in many operations
foreach(data_source() as $data) {
    $final .= $data;
}

?>

See also PHP 7 performance improvements (3/5): Encapsed strings optimization.

1.2.61.1. Suggestions

  • Collect all pieces in an array, then implode() the array in one call.

1.2.61.2. Specs

Short name

Performances/NoConcatInLoop

Rulesets

All, Changed Behavior, Performances, Top10

Exakat since

0.12.4

PHP Version

All

Severity

Major

Time To Fix

Slow (1 hour)

Precision

Very high

Features

loop

Examples

SuiteCrm, ThinkPHP

Available in

Entreprise Edition, Exakat Cloud