Question

I reviewed my compiled code with javac command line and I saw whenever I used String concatenation with + operator, compiled code replaced with StringBuilder's append() method. now I think using StringBuilder and String concatenation have same performance because they have similar bytecode, is it correct?

Was it helpful?

Solution

Yeah, it is true! But when you concatenate in loop the behaviour differs. e.g.

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

new StringBuilder will be constructed at every single loop iteration (with initial value of str) and at the end of every iteration there will be concatenation with initial String (actually StringBuilder with initial value of str).
So you need to create StringBuilder by yourself only when you work with String concatenation in loop.

OTHER TIPS

The main difference (and the reason the compiler uses StringBuilder for string concatenation) is that String is immutable, whereas StringBuilder isn't.

For example, computing s1 + s2 + s3 using strings alone would require s1's characters to be copied twice. This can be (and is) avoided by using StringBuilder.

This optimization is explicitly permitted by the JLS:

An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top