I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty StringBuilder
, but I can't see any method similar to the .NET StringBuilder.Clear in the documentation, just the delete method which seems overly complicated.
So what is the best way to clean out a StringBuilder
in Java?
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.
Clear Method is used to remove all the characters from the current StringBuilder instance.
StringBuffer: Java is popular. Updated StringBuffer: In the above example, we have used the delete() method of the StringBuffer class to clear the string buffer. Here, the delete() method removes all the characters within the specified index numbers.
Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.
Two ways that work:
stringBuilderObj.setLength(0)
.new StringBuilder()
instead of clearing the buffer. Note that for performance-critical code paths, this approach can be significantly slower than the setLength
-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).There are basically two alternatives, using setLength(0)
to reset the StringBuilder or creating a new one in each iteration. Both can have pros and cons depending on the usage.
If you know the expected capacity of the StringBuilder beforehand, creating a new one each time should be just as fast as setting a new length. It will also help the garbage collector, since each StringBuilder will be relatively short-lived and the gc is optimized for that.
When you don't know the capacity, reusing the same StringBuilder might be faster. Each time you exceed the capacity when appending, a new backing array has to be allocated and the previous content has to be copied. By reusing the same StringBuilder, it will reach the needed capacity after some iterations and there won't be any copying thereafter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With