PHP › Strings & String Functions

How can regular string concatenation inside a large loop lead to performance problems, and what alternative approaches help avoid this issue when building up very large strings?

Advanced

Answer

Repeatedly concatenating onto a string inside a loop that runs many thousands of times can become inefficient in some scenarios, since each concatenation may involve creating a new string in memory rather than simply extending the existing one, and for building up very large amounts of text, an alternative approach is to collect each individual piece into an array first, then join every element together at once using the implode function after the loop completes, which is typically both faster and clearer than building the same result through many repeated individual concatenation operations.
$parts = [];
foreach ($items as $item) {
    $parts[] = formatItem($item);
}
$result = implode("\n", $parts);
Real-world example A script generating a very large CSV export file collects each formatted row into an array first and joins them all together once at the very end with implode, noticeably improving performance compared to concatenating each row directly onto a single growing string throughout the loop.

Common follow-ups: Does this performance concern apply equally to every version of PHP, given ongoing internal engine optimizations?;What other common patterns help improve the performance of heavy text processing code?