2

Possible Duplicate:
java String concatenation
StringBuilder vs String concatenation in toString() in Java

I ve read some articles about append() is much faster than +, but what is the reason ,and why would we use + over append()at all? Thanks!

Community
  • 1
  • 1
sammiwei
  • 3,140
  • 9
  • 41
  • 53
  • 3
    have a look at http://stackoverflow.com/questions/47605/java-string-concatenation and just search about java string concatenation, it's a topic that has been discussed many times. – yurib Jan 25 '12 at 00:39
  • This has been asked numerous times http://stackoverflow.com/q/4648607/776084 – RanRag Jan 25 '12 at 00:42

4 Answers4

6

+ creates new intermediate String ojectss as Strings are immutable in Java where as StringBuffer's append() works on the same string and that is why it is considered faster. However, you should use StringBuilder from java 5 on wards as it is said to be faster than StringBuffer as it's methods are not synchronized like StringBuffer.

This is high level theoritical explanation. For more specific details look at String concatenation: concat() vs "+" operator post.

Community
  • 1
  • 1
Aravind Yarram
  • 78,777
  • 46
  • 231
  • 327
2

If your code isn't executed in a loop many thousand times, + is perfectly okay. Exception to the rule, an ever growing string, with reallocation of memory over and over again:

// fine:
for (customer: list)
    System.out.println ("Customer: " + customer);

// prolematic for bigger lists:
for (word: list)
     chain += word;

With 100 words of length 50, you end up with lengths 50, 100, 150, ... 5000 - totally 250 000 chars, a lot of work for the garbage collection.

user unknown
  • 35,537
  • 11
  • 75
  • 121
1

Just concatentating 2 strings total (no loops) then using + is usually faster. If you are joining more than 2 strings total then append() is faster.

The difference is that the string buffer uses a char[] internally and has extra (free) space in that array to put new appended content into (the array grows if it is too small). The + operator actually has to create a new string of the correct length and then copy the left hand side and right hand side into it.

diolemo
  • 2,621
  • 2
  • 21
  • 28
1

If you're compiling for JDK 1.5 or later, concatenation turns into a StringBuilder, instead of a StringBuffer. StringBuilder is optimized for concatenation of local variables (ie, it is lock-free). So the link Greg Mattes references above is probably the question you really wanted to ask.

Jason
  • 3,021
  • 1
  • 23
  • 25