Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear or empty a StringBuilder? [duplicate]

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?

like image 558
Hans Olsson Avatar asked Mar 04 '11 10:03

Hans Olsson


People also ask

How do you clear a StringBuilder?

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.

How do I remove all elements from string builder?

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

How do you clear a StringBuffer?

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.

How do I know if my StringBuilder is empty?

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.


2 Answers

Two ways that work:

  1. Use stringBuilderObj.setLength(0).
  2. Allocate a new one with 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).
like image 139
Marcus Frödin Avatar answered Sep 29 '22 07:09

Marcus Frödin


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.

like image 38
Jörn Horstmann Avatar answered Sep 29 '22 06:09

Jörn Horstmann