String concatenation vs. Array joins

I’ve read several websites which claim that string concatenation is outperformed by array joining in PHP. I know from firsthand that this certainly is a fact in ASP. And it’s considered a ‘best practice’ in Javascript and probably several other languages. But PHP has always been a bit different on some parts, so I decided to test this and came to some interesting conclusions.

The following tests were performed 50 times with PHP 5.2.6.

First I tested the following pieces of code for parse time, $iConcats was set to 5000:

for($i=0; $i<$iConcats; ++$i)
{
$o .= ‘aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa’;
}

This parsed on avarage in 0.0065 seconds.
Next up was the array equivalent:

for($i=0; $i<$iConcats; ++$i)
{
$a[] = ‘aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa’;
}
$a = join(”, $a);

This parsed on average in about 0.0187 seconds. That’s almost 3 times slower!
I deliberately added the join statement as it completes the comparison. And dor the more visually oriented amongst us, google provides nice graphs:

Who doesn't like pie?

During the measurements I also tracked the memory usage, which had the same outcome, concatenation wins again.

For string concatenation memory usage was ~56Mb. The array version used up ~155Mb. Again the three times! And again, let’s look at some graphs:

And in pie:

So in conclusion (at least for PHP 5.2.6) string concatenation is faster than array joins!

Strings vs Arrays: 2-0.

If you have some test resutls you want to share, please respond below or send me an email, you can reach me at: korneelwever. I’m with the Google mail service ;-).

Leave a Comment

*

*