A common tendency of Java programmers is to always concatenate Strings using + operator. Which is actually very good, and simplifies the code by improves readability, since we would have to use StringBuilder.append(String), if the single + operator was not allowed.
In fact if we look in byte code generate from such concatenation style, we will see a StringBuilder being used to perform the action.
Check the JSL: JLS
Now, the point is, although this facility, you should not use the + operator in loop concatenation.
Why?
A new
So you need to create StringBuilder by yourself only when you work with String concatenation in loop.
Let us procuce the evidence
First, run this code, and see how long it takes to be executed:
Now, bellow is the code you should stick with, run it and evidence the improvement.
Notice the StringBuilder being created right beforer the for loop.
Needless to say...
you should not use the + operator in loop concatenation
In fact if we look in byte code generate from such concatenation style, we will see a StringBuilder being used to perform the action.
Check the JSL: JLS
Now, the point is, although this facility, you should not use the + operator in loop concatenation.
Why?
A new
StringBuilder
Object 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.
Let us procuce the evidence
First, run this code, and see how long it takes to be executed:
Now, bellow is the code you should stick with, run it and evidence the improvement.
Notice the StringBuilder being created right beforer the for loop.
Needless to say...
you should not use the + operator in loop concatenation
Comments
Post a Comment