Clearing a string buffer/builder after loop

JavaStringBuffer

Java Problem Overview


How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?

Java Solutions


Solution 1 - Java

One option is to use the delete method as follows:

StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
   sb.append("a");

   // This will clear the buffer
   sb.delete(0, sb.length());
}

Another option (bit cleaner) uses setLength(int len):

sb.setLength(0);

See Javadoc for more info:

Solution 2 - Java

The easiest way to reuse the StringBuffer is to use the method setLength()

public void setLength(int newLength)

You may have the case like

StringBuffer sb = new StringBuffer("HelloWorld");
// after many iterations and manipulations
sb.setLength(0);
// reuse sb

Solution 3 - Java

You have two options:

Either use:

sb.setLength(0);  // It will just discard the previous data, which will be garbage collected later.  

Or use:

sb.delete(0, sb.length());  // A bit slower as it is used to delete sub sequence.  

NOTE

Avoid declaring StringBuffer or StringBuilder objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.

Solution 4 - Java

public void clear(StringBuilder s) {
    s.setLength(0);
}

Usage:

StringBuilder v = new StringBuilder();
clear(v);

for readability, I think this is the best solution.

Solution 5 - Java

I suggest creating a new StringBuffer (or even better, StringBuilder) for each iteration. The performance difference is really negligible, but your code will be shorter and simpler.

Solution 6 - Java

buf.delete(0,  buf.length());

Solution 7 - Java

Already good answer there. Just add a benchmark result for StringBuffer and StringBuild performance difference use new instance in loop or use setLength(0) in loop.

The summary is: In a large loop

  • StringBuilder is much faster than StringBuffer
  • Create new StringBuilder instance in loop have no difference with setLength(0). (setLength(0) have very very very tiny advantage than create new instance.)
  • StringBuffer is slower than StringBuilder by create new instance in loop
  • setLength(0) of StringBuffer is extremely slower than create new instance in loop.

Very simple benchmark (I just manually changed the code and do different test ):

public class StringBuilderSpeed {
public static final char ch[] = new char[]{'a','b','c','d','e','f','g','h','i'};

public static void main(String a[]){
	int loopTime = 99999999;
	long startTime = System.currentTimeMillis();
	StringBuilder sb = new StringBuilder();
	for(int i = 0 ; i < loopTime; i++){
		for(char c : ch){
			sb.append(c);
		}
		sb.setLength(0);
	}
	long endTime = System.currentTimeMillis();
	System.out.println("Time cost: " + (endTime - startTime));
}

}

New StringBuilder instance in loop: Time cost: 3693, 3862, 3624, 3742

StringBuilder setLength: Time cost: 3465, 3421, 3557, 3408

New StringBuffer instance in loop: Time cost: 8327, 8324, 8284

StringBuffer setLength Time cost: 22878, 23017, 22894

Again StringBuilder setLength to ensure not my labtop got some issue to use such long for StringBuffer setLength :-) Time cost: 3448

Solution 8 - Java

StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();

i think this code is faster.

Solution 9 - Java

I used this below code to store password for temporary processing like regex matching and clear it once done. The usual delete method does not reset all the characters, which was not suitable for me. This code satisfied my requirement.

    public static void clear(StringBuilder value) {
        for (int i = 0, len = value.length(); i < len; i++) {
            value.setCharAt(i, Character.MIN_VALUE);
        }
        value.setLength(0);
    }

    public static void main(String[] args) {
        StringBuilder sb = new StringBuilder("clear this password");
        // use & process sb
        clear(sb);
    }

Solution 10 - Java

I think the best way to clear StringBuilder is Clear() method.
StringBuilder sb = new StringBuilder(); sb.Clear();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwaterfallrainView Question on Stackoverflow
Solution 1 - JavaJonView Answer on Stackoverflow
Solution 2 - JavaMossaddeque MahmoodView Answer on Stackoverflow
Solution 3 - JavaAditya SinghView Answer on Stackoverflow
Solution 4 - JavaIdo KesslerView Answer on Stackoverflow
Solution 5 - JavaEli AcherkanView Answer on Stackoverflow
Solution 6 - JavaSuraj ChandranView Answer on Stackoverflow
Solution 7 - JavaHaoView Answer on Stackoverflow
Solution 8 - JavaBinh PhungView Answer on Stackoverflow
Solution 9 - JavaRahogataView Answer on Stackoverflow
Solution 10 - JavaM2012View Answer on Stackoverflow