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!
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!
+
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.
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.
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.
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.