This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Question: How do I empty StringBuilder?

I use StringBuilder in loops, and every X iteration I want to empty it and start with an empty StringBuilder, but I don’t see anything that looks like. NET stringBuilder. CLEAR method. Delete () in the document looks overly complicated

So what’s the best way to clean up StringBuilder in Java?

Answer a

There are basically two options

  1. setLength(0)resetStringBuilder
  2. Create a new one in each iterationStringBuilder.

Both have advantages and disadvantages, depending on how you use them

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

It may be faster to reuse the same StringBuilder if you don’t know the capacity. Each time an append exceeds capacity, a new array must be allocated and the previous contents copied to the new array. By reusing the StringBuilder, it will reach the desired capacity after a few iterations, and there will be no array copying after that.

Answer two

I think many of the answers here may be missing a high-quality method included in StringBuilder: delete(int start, int end).

Now suppose you have a variable called StringBuilder Table and you want to modify it dynamically in your program (one requirement I’m working on now does this).

StringBuilder table = new StringBuilder();
Copy the code

If you want to use a StringBuilder object in a loop method, clean up the StringBuilder for next use

table.delete(int start, int end). 
Copy the code

Start and end are the index of the characters you want to delete. What if you don’t know the length and want to delete everything?

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

StringBuilder can take up a lot of overhead when changing frequently and can cause thread-safety issues. If your interface is user-facing, use A StringBuffer that functions like StringBuilder

class MyLogger {
    StringBuilder strBldr = new StringBuilder(256);

    public void logMsg( String stuff, SomeLogWriterClass log ) {

        // zero out strBldr's internal index count, not every
        // index in strBldr's internal buffer
        strBldr.setLength(0);

        // ... append status level
        strBldr.append("Info");

        // ... append ' ' followed by timestamp
        // assuming getTimestamp() returns a String
        strBldr.append(' ').append(getTimestamp());

        // ... append ':' followed by user message
        strBldr.append(':').append(msg);

        log.write(strBldr.toString());
    }
}
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/5…