Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder - Reset or create a new

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.

like image 460
Chandru Avatar asked Sep 12 '13 14:09

Chandru


People also ask

How do you clear a StringBuilder?

Using setLength() method A simple solution to clear a StringBuilder / StringBuffer in Java is calling the setLength(0) method on its instance, which causes its length to change to 0. The setLength() method fills the array used for character storage with zeros and sets the count of characters used to the given length.

Does StringBuilder create new string?

StringBuilder will only create a new string when toString() is called on it. Until then, it keeps an char[] array of all the elements added to it. Any operation you perform, like insert or reverse is performed on that array.

How do I remove all elements from string builder?

Clear Method is used to remove all the characters from the current StringBuilder instance.

Does StringBuilder need to be disposed?

No, a StringBuilder is a purely managed resource. You should just get rid of all references to it.


1 Answers

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 
like image 69
anubhava Avatar answered Sep 19 '22 02:09

anubhava