

Java String Concatenation and Performance - edw519
http://www.venishjoe.net/2009/11/java-string-concatenation-and.html

======
m0th87
Maybe I've been away from Java for too long, but I understand why the +
operator's implementation is so much slower than that of String.concat(). If
concat() uses a StringBuilder, why doesn't the + operator as well?

~~~
mustpax
\+ operator does use StringBuilder. But it will use a StringBuilder for _each_
string expression. Take the following piece of code:

    
    
      String foo = "";
      for (int i = 0; i < 1000; i++) {
        foo += "x";
      }
    

The inside of the for loop can be replaced with:

    
    
      StringBuilder tmp = new StringBuilder(foo.length());
      tmp.append("x");
      foo = tmp.toString()
    

As you will notice, we are still copying over the string foo each time we
concatenate. So building strings with + inside a loop will still give you the
feared copy-string-each-time behavior. The new String.concat() trick is only
useful for crafting long strings in a single go, i.e. in a single expression.

~~~
jkb112
The author has updated the post, string concat takes significantly more
compared to the buffer or builder

------
nl
It's not as simple as he makes out. I had a look at the + operator and
compiler optimizations back in 2005. Basically, depending on exactly how you
setup your strings javac is able to do some optimization. Note that this is a
compile time optimization, so compiling with Eclipse (for example) will
probably give different result.

Anyway, some details are at [http://nicklothian.com/blog/2005/06/09/on-java-
string-concat...](http://nicklothian.com/blog/2005/06/09/on-java-string-
concatenation/)

------
potatolicious
And this is why I reject the argument that higher-level programmers don't need
to know lower-level things. The string concat issue in particular is something
_every single_ Java developer needs to know. I've successfully taken 6-day
jobs down toe 3.5h with this alone.

