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