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.
StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.
I think we should go with StringBuilder append approach. Reason being : The String concatenate will create a new string object each time (As String is immutable object) , so it will create 3 objects. With String builder only one object will created[StringBuilder is mutable] and the further string gets appended to it.
StringBuilder in Java is a class used to create a mutable, or in other words, a modifiable succession of characters. Like StringBuffer, the StringBuilder class is an alternative to the Java Strings Class, as the Strings class provides an immutable succession of characters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With