I have the following code:
StringBuilder str = new StringBuilder("foo"); for(Field f : fields){ str.append("|" + f); } str.append("|" + bar); String result = str.toString();
I know compiler will optimize string concatenation "|" + f
and replace it with StringBuilder. However will a new StringBuilder be created or the existing str
will be used in Java 8? How about Java 9?
As a consequence, a Java compiler is not required to optimize string concatenation, though all tend to do so as long as no loops are involved. You can check the extent of such compile time optimizations by using javap (the java decompiler included with the JDK).
Note that regular string concatenations are faster than using the StringBuilder but only when you're using a few of them at a time. If you are using two or three string concatenations, use a string.
Each time strcat calls, the loop will run from start to finish; the longer the string, the longer the loop runs. Until the string is extensive, the string addition takes place very heavy and slow.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
By default in java-9 there will be no StringBuilder
for string concatenation; it is a runtime decision how it's made via the invokedynamic
. And the default policy is not a StringBuilder::append
one.
You can also read more here.
Under java-8 a new one will be created (really easy to spot two occurrences of invokespecial // Method java/lang/StringBuilder."<init>":()V
in the de-compiled bytecode.
Also, you have a suggestion about append.append...
; just notice that this is much better than sb.append ... sb.append
, and here is why.
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