Possible Duplicate:
java String concatenation
Sources tell us that concat is implemented as follows:
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
Does + implementation differ when it comes to Strings? How? Is there a performance difference between + and concat. When should one be chosen over another?
This is a test I just made:
I created a class with those 3 instructions:
Then I took the generated .class file and I decompiled using JAD decompiler.
This is how the code show up in the regenerated source:
So: this is the difference between + and concat.
I guess concat() is always better than StringBuilder, because it requires less objects to be created. You may chose StringBuilder if you want to append string repeatedly in a loop; in this case concat may create a new String each time, while StringBuilder may just expand the internal buffer. But, if StringBuilder is best in this last scenario, we can say that still concat() is better than +, in loops.