Programming
Article
By Craig Buckler

High-Performance String Concatenation in PHP

By Craig Buckler

We recently examined the complexities of fast string concatenation in JavaScript so I thought it would be useful to repeat the exercise for PHP. This could be a more important to your application: large string operations are often handled on the server when generating HTML pages.

There are no special libraries in the standard PHP installation and string concatenation is implemented using the dot operator:


$str = 'a' . 'b';
$str .= 'c';

You can also join an array of strings using the implode function (or it’s alias, join):


$str = implode(array('a', 'b', 'c'));

If you’re only joining a few strings, you should use whichever method is most practical. Readability and functionality is always more important than negligible performance gains.

Concatenating many strings

Consider the following functionally identical examples. The first uses a string concatenation operator:


// standard string append
$str = '';
for ($i = 30000; $i > 0; $i--) {
	$str .= 'String concatenation. ';
}

The second uses an array join:


// array join
$str = '';
$sArr = array();
for ($i = 30000; $i > 0; $i--) {
	$sArr[] = 'String concatenation. ';
}
$str = implode($sArr);

Which is fastest?

The good news is that PHP5 is quick. I tested version 5.3 and you’re far more likely to run out of memory than experience performance issues. However, the array implode method typically takes twice as long as the standard concatenation operator. A comparable period of time is required to concatenate the string or build the array, but the implode function doubles the effort.

Unsurprisingly, PHP is optimized for string handling and the dot operator will be the fastest concatenation method in most cases.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account