StringBuilder - Reset or create a new

Chandru picture Chandru · Sep 12, 2013 · Viewed 37k times · Source

I have a condition that a StringBuilder keeps storing lines matching a pattern from a large flat file (100's of MB). However after reaching a condition I write the content of the StringBuilder varialble to a textfile.

Now I wonder if I should use the same variable by resetting the object ->

stringBuilder.delete(0,stringBuilder.length())

OR

stringBuilder=new StringBuilder();

Please suggest which would do you think is better as far as both performance and OOM issues are concerned.

Answer

anubhava picture anubhava · Sep 12, 2013

I think StringBuilder#delete(start, end) is still expensive call, you should do:

stringBuilder.setLength(0);

to reset it.


UPDATE: After looking at source code of StringBuilder It seems setLength(int) leaves old buffer intact and it is better to call: StringBuilder#trimToSize() after above call which attempts to reduce storage used for the character sequence.

So something like this would be more efficient:

stringBuilder.setLength(0); // set length of buffer to 0
stringBuilder.trimToSize(); // trim the underlying buffer