Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does String concatenation get optimized to use existing StringBuilders?

Tags:

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?

like image 762
Anton Krosnev Avatar asked Jul 26 '17 10:07

Anton Krosnev


People also ask

Does Java compiler optimize string concatenation?

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).

Which is faster string concatenation or the StringBuilder class?

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.

Is string concatenation slow?

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.

Why StringBuilder is faster than string concatenation?

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.


1 Answers

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.

like image 161
Eugene Avatar answered Oct 05 '22 13:10

Eugene