snippetjavaCritical
How can I clear or empty a StringBuilder?
Viewed 0 times
emptyhowstringbuilderclearcan
Problem
I'm using a StringBuilder in a loop and every x iterations I want to empty it and start with an empty
So what is the best way to clean out a
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?Solution
Two ways that work:
- Use
stringBuilderObj.setLength(0).
- 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 thesetLength-based approach (since a new object with a new buffer needs to be allocated, the old object becomes eligible for GC etc).
Context
Stack Overflow Q#5192512, score: 994
Revisions (0)
No revisions yet.