This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

How do I clear or empty the StringBuilder?

I use StringBuilder in the loop, and every x iteration I want to empty it and start StringBuilder with empty, but I don’t see anything in the documentation that looks like this. NET StringBuilder.Clear method, just don’t see delete method too complex.

So what’s the best way for StringBuilder to clean up A with Java?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

Two ways of working:

Using stringBuilderObj. SetLength (0)

Allocate a new StringBuilder() instead of clearing the buffer. Note that for performance-critical code paths, this approach can be much slower than setLength based methods (because new objects with new buffers need to be allocated, so old objects can use GC, etc.).

Answer:

There are basically two options, setLength(0) to reset the StringBuilder or to create a new one with each iteration. Both have advantages and disadvantages, depending on usage.

If you know the expected capacity of the StringBuilder in advance, creating a new capacity each time should be as fast as setting a new length. It will also help the garbage collector because each StringBuilder has a relatively short lifetime and the GC is optimized for that.

It may be faster to reuse the same StringBuilder when you don’t know the capacity. Each time capacity is exceeded on add, a new backup array must be allocated, and the previous content must be copied. By using the same StringBuilder repeatedly, it will reach the required capacity after some iterations, after which no more copies will be made.

Answer:

Delete is less complicated:

myStringBuilder.delete(0, myStringBuilder.length());
Copy the code

You can also:

myStringBuilder.setLength(0);
Copy the code

The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 5…

The author suggests: New new, or set the length to 0


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️