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.
First
StringBufferis thread-safe which will have bad performance compared toStringBuilder. StringBuilder is not thread safe but as a result is faster. Finally, I prefer just setting the length to 0 using setLength.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 newStringBuilder(or StringBuffer) would be less efficient. Any time you seenewJava is creating a new object and placing that on the heap.Note: After looking at the implementation of
.deleteand.setLength,.deletesets length = 0, and.setLengthsets every thing to'\0'So you may get a little win with.delete