You want to use StringBuilder if you are concatenating a string in a loop (of a larger number).
for(int i = 0; i < 10000; i++){ over_9000_blahs += "blah"; }
What does this mean for each iteration :
- Creates a new
StringBuilder internally with an internal char array large enough to accommodate the intermediate result ( over_9000_blahs ) - Copy characters from
over_9000_blahs to an internal array - Copy characters from
"blah" - Creates a new
String , copying characters from the internal array again
So, these are two copies of a longer string per iteration - this means the quadratic complexity of time.
Since System.out.println() can be synchronized , it is likely that its call will repeat more slowly than using StringBuilder (but I assume that it will not be slower than concatenating a string in a loop with += ).
So the StringBuilder approach should be the best of three.
Jiri tousek
source share