According to JSL - Java Specification Language
15.18.1. String Concatenation Operator +
The operator '+' offers the facility of being a single character to concatenate Strings, and its use is enconrajado. Actually when the compiler is compiled the compiler switches to a Stringbuilder
Although this is a valuable resource, it should not be used in loops like the above question.
Why?
A new Stringbuilder will be created at each iteration (with the initial str value) and at the end of each iteration, there will be concatenation with the initial String (actually Stringbuilder with str initial value).
So, you should create Stringbuilder ourselves only when we are concatenating Strings into loops.
See how the code should look, compare the performance of both, is shocking, the faster the program gets:
public static void main(String... args) {
long initialTime = System.currentTimeMillis();
String s = "a";
StringBuilder strBuilder = new StringBuilder(s);
for (int i = 0; i < 100000; i++) {
strBuilder.append("a");
}
System.out.println("Total time: " + (System.currentTimeMillis() - initialTime));
}
Source:
http://jknowledgecenter.blogspot.com.br/2015/05/always-use-stringbuilder-while.html
+1 And for those who are interested, I "decompiled" the codes above (slightly modified) and found that - in the bytecodes (compiled on Ubuntu -
javac 1.7.0_79
) - in fact a newStringBuilder
is created with each loop iteration.– mgibsonbr
Yes, it’s amazing the compiler should infer a unique Stringbuilder.
– Filipe Miranda
Using Stringbuilder: Total time: 5,106,995 (nano Seconds) (5 million) Using '+': Total time: 4,192,903,645 (nano Seconds) (4 BILLION) Huge difference...
– user22408
Very good. Vinvendo and learn"e"ndendo.
– Cold
A curiosity: The sonarQube generates an Issue in concatenations within loops with
+
"In each iteration, the String is converted to a Stringbuffer/Stringbuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the Growing string is recopied in each iteration. Better performance can be obtained by using a Stringbuffer (or Stringbuilder in Java 1.5) explicitly."– Daniela Morais