When to use StringBuilder in Java

JavaStringPerformance

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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 Strings, because the compiler will use StringBuilder automatically.

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

Have a look at: http://www.javaspecialists.eu/archive/Issue068.html and http://www.javaspecialists.eu/archive/Issue105.html

Do the same tests in your environment and check if newer JDK or your Java implementation do some type of string operation better with String or better with StringBuilder.

Solution 5 - Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

Solution 6 - Java

The + operator uses public String concat(String str) internally. This method copies the characters of the two strings, so it has memory requirements and runtime complexity proportional to the length of the two strings. StringBuilder works more efficent.

However I have read here that the concatination code using the + operater is changed to StringBuilder on post Java 4 compilers. So this might not be an issue at all. (Though I would really check this statement if I depend on it in my code!)

Solution 7 - Java

For two strings concat is faster, in other cases StringBuilder is a better choice, see my explanation in https://stackoverflow.com/questions/8755063/concatenation-operator-vs-concat/13739225#13739225

Solution 8 - Java

The problem with String concatenation is that it leads to copying of the String object with all the associated cost. StringBuilder is not threadsafe and is therefore faster than StringBuffer, which used to be the preferred choice before Java 5. As a rule of thumb, you should not do String concatenation in a loop, which will be called often. I guess doing a few concatenations here and there will not hurt you as long as you are not talking about hundreds and this of course depends on your performance requirements. If you are doing real time stuff, you should be very careful.

Solution 9 - Java

The Microsoft certification material addresses this same question. In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. I would assume a similar answer for Java strings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkostjaView Question on Stackoverflow
Solution 1 - JavaRalphView Answer on Stackoverflow
Solution 2 - JavazawhtutView Answer on Stackoverflow
Solution 3 - JavaRiaan CorneliusView Answer on Stackoverflow
Solution 4 - JavaMichał NiklasView Answer on Stackoverflow
Solution 5 - JavaWilliam MorrisonView Answer on Stackoverflow
Solution 6 - JavaspaView Answer on Stackoverflow
Solution 7 - JavaEvgeniy DorofeevView Answer on Stackoverflow
Solution 8 - JavaNaviView Answer on Stackoverflow
Solution 9 - JavaBabak NaffasView Answer on Stackoverflow