StringBuffer and append method

166 views Asked by At

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(" ");
}
2

There are 2 answers

1
dkatzel On BEST ANSWER

The first version will actually get compiled into something like this:

for (int i = 0; i <= max; i++) {

    result.append( new StringBuilder(numbers[i]).append(" ").toString() );

}

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 of StringBuffer since StringBuffers synchronize and you appear to only be using it in a single thread.

0
markspace On

The first one is slower. Any time you create a new object and then have to garbage collect it, it's going to add some overhead and slow your system down. The second one is faster -- maybe not a lot but it is faster -- and I'd use it myself instead of the first.