Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: String concat in bytecode converted to StringBuilder

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?

like image 374
Hamid Samani Avatar asked Dec 11 '22 16:12

Hamid Samani


1 Answers

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.

like image 67
Sergey_Klochkov Avatar answered Mar 18 '23 18:03

Sergey_Klochkov