Skip to main content

High-Performance String Concatenation in PHP

By Craig Buckler

Programming

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

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.

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

New books out now!

Learn how Git works, and how to use it to streamline your workflow!


Google, Netflix and ILM are Python users. Maybe you should too?