You want to use StringBuilder
if you're concatenating string in a (larger count) loop.
for(int i = 0; i < 10000; i++){
over_9000_blahs += "blah";
}
What this does is for each iteration:
- Creates a new
StringBuilder
internally with internal char
array large enough to accommodate the intermediate result (over_9000_blahs
)
- Copies the characters from
over_9000_blahs
into the internal array
- Copies the characters from
"blah"
- Creates a new
String
, copying the characters from internal array again
So that is two copies of the increasingly long string per iteration - that means quadratic time complexity.
Since System.out.println()
might be synchronized, there's a chance that calling it repeatedly will be slower than using StringBuilder
(but my guess would be it won't be slower than concatenating the string in the loop using +=
).
So the StringBuilder
approach should be the best of the three.