Does the following slow the performance of append
method and how many String objects are created in the append
?
long[] numbers = new long[20];
StringBuffer result = new StringBuffer(20);
for (int i = 0; i <= max; i++) {
result.append(numbers[i] + " ");
}
System.out.println(result);
I mean if Strings are immutable, the append method should create one for numbers[i]
then another one for the space " "
, combine them into a a final one and garbage collect the two ? Am I wrong ? Is the plus sign an overkill here or should I use the following:
for (int i = 0; i <= max; i++) {
result.append(numbers[i]);
result.append(" ");
}
The first version will actually get compiled into something like this:
so you can see we are creating a whole new
StringBuilder
at each iteration then throwing it away.so your second version is much better since it will only use 1 StringBuffer.
I would also recommend that you use a
StringBuilder
instead ofStringBuffer
sinceStringBuffers
synchronize and you appear to only be using it in a single thread.