When to use StringBuilder in Java [duplicate]
It is supposed to be generally preferable to use a StringBuilder
for string concatenation in Java. Is this always the case?
What I mean is this: Is the overhead of creating a StringBuilder
object, calling the append()
method and finally toString()
already smaller then concatenating existing strings with the +
operator for two strings, or is it only advisable for more (than two) strings?
If there is such a threshold, what does it depend on (perhaps the string length, but in which way)?
And finally, would you trade the readability and conciseness of the +
concatenation for the performance of the StringBuilder
in smaller cases like two, three or four strings?
Explicit use of StringBuilder
for regular concatenations is being mentioned as obsolete at obsolete Java optimization tips as well as at Java urban myths.
If you use String concatenation in a loop, something like this,
String s = "";
for (int i = 0; i < 100; i++) {
s += ", " + i;
}
then you should use a StringBuilder
(not StringBuffer
) instead of a String
, because it is much faster and consumes less memory.
If you have a single statement,
String s = "1, " + "2, " + "3, " + "4, " ...;
then you can use String
s, because the compiler will use StringBuilder
automatically.
Ralph's answer is fabulous. I would rather use StringBuilder class to build/decorate the String because the usage of it is more look like Builder pattern.
public String decorateTheString(String orgStr){
StringBuilder builder = new StringBuilder();
builder.append(orgStr);
builder.deleteCharAt(orgStr.length()-1);
builder.insert(0,builder.hashCode());
return builder.toString();
}
It can be use as a helper/builder to build the String, not the String itself.
As a general rule, always use the more readable code and only refactor if performance is an issue. In this specific case, most recent JDK's will actually optimize the code into the StringBuilder version in any case.
You usually only really need to do it manually if you are doing string concatenation in a loop or in some complex code that the compiler can't easily optimize.