What is more efficient StringBuffer new() or delete(0, sb.length())?

Jérôme Verstrynge picture Jérôme Verstrynge · Aug 24, 2011 · Viewed 13.1k times · Source

It is often argued that avoiding creating objects (especially in loops) is considered good practice.

Then, what is most efficient regarding StringBuffer?

StringBuffer sb = new StringBuffer();
ObjectInputStream ois = ...;

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

    for (j=0;i<10;j++) {
        sb.append(ois.readUTF());
    }
    ...

    // Which option is the most efficient? 
    sb = new StringBuffer(); // new StringBuffer instance?
    sb.delete(0,sb.length()); // or deleting content?

}

I mean, one could argue that creating an object is faster then looping through an array.

Answer

Amir Raminfar picture Amir Raminfar · Aug 24, 2011

First StringBuffer is thread-safe which will have bad performance compared to StringBuilder. StringBuilder is not thread safe but as a result is faster. Finally, I prefer just setting the length to 0 using setLength.

sb.setLength(0)

This is similar to .delete(...) except you don't really care about the length. Also probably a little faster since it doesn't need to 'delete' anything. Creating a new StringBuilder (or StringBuffer) would be less efficient. Any time you see new Java is creating a new object and placing that on the heap.

Note: After looking at the implementation of .delete and .setLength, .delete sets length = 0, and .setLength sets every thing to '\0' So you may get a little win with .delete