PHP String Concatentation Performance

I’m not sure if this is totally correct and I have no fixed way of measuring this (other than that I don’t get any timeout errors anymore) but I’ve noticed a significant difference when choosing between two different methods of string concatenation:

Slow way:

foreach($oranges as $orange){
$orange_str = $orange_str . $orange;
}

Better way:

foreach($oranges as $orange){
$orange_str .= $orange;
}

This is obviously simplified for example’s sake, but I had a situation where I was concatenating several hundred (maybe a thousand) elements to a string and I was receiving a “Fatal error: Maximum execution time of 30 seconds exceeded…”.  My best guess is that with the first method, an actual copy of that string is being made in memory so you’re probably taking up twice the amount of memory than you should be.  That’s just my guess.

2 Comments to “PHP String Concatentation Performance”

  1. Johnny156 17 April 2009 at 3:39 pm #

    What is more likely the case, is in that first way you are actually creating a new string when you concat on $orange_str. While $orange_str .= actually appends to the existing string. This depends on the language. (i.e. Java strings are immutable so when you do += on a java string it actually has to make a brand new string)

  2. z 18 April 2009 at 12:12 am #

    why not try an implode()?
    [this is assuming that you're trying concat with an array of course, and my assumption is based on your "foreach" statement]
    it’s a native function, and may work to your benefit

    example:
    $orange = array(“orange”, “you”, “glad”, “i”, “didn’t”, “say”, “banana”);
    $orange_str = implode(” “, $orange);
    echo $orange_str; // “orange you glad i didn’t say banana”

    doesn’t hurt to try. also, if you don’t like the word implode, you could simply use join() [i like this better because it's like python =)]


Leave a Reply