Java: String concat in bytecode converted to StringBuilder

I looked at my compiled code using the javac command line, and I saw when I used String concatenation with the + operator, the compiled code was replaced with the StringBuilder append () method. now I think that using StringBuilder and String concatenation have the same performance because they have the same bytecode, is this correct?

+4
source share
2 answers

Yes it's true! But when you concatenate in a loop, the behavior is different. eg

String str = "Some string"; for (int i = 0; i < 10; i++) { str += i; } 

new StringBuilder will be built on each iteration of the loop (with the initial value of str), and at the end of each iteration there will be a concatenation with the initial string (actually StringBuilder with the initial value of str ).
Therefore, you need to create a StringBuilder yourself only when you work with String concatenation in a loop.

+12
source

The main difference (and the reason the compiler uses StringBuilder to concatenate strings) is that String is immutable, while StringBuilder not.

For example, to calculate s1 + s2 + s3 using only strings, you would need to copy two s1 characters. This can be avoided (s) by using StringBuilder .

This optimization is explicitly permitted by JLS :

An implementation may decide to perform the conversion and concatenation in one step to avoid creating and then dropping the intermediate String object. To increase string re-concatenation performance, the Java compiler can use the StringBuffer class or a similar method to reduce the number of intermediate String objects created when evaluating an expression.

0
source

All Articles