0

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
  • You pretty much answered your own question :). Second snippet is definitely the way to go. Commented Dec 1, 2014 at 19:29
  • The latter would be better :) Commented Dec 1, 2014 at 19:29

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+ for showing the resulting compiled code (i was to slow with my answer) and + for recommend to use StringBuilder with focus that StringBuffer are syncronize
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.