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:
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
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! ❤ ️ ❤ ️ ❤ ️ ❤ ️