views:

543

answers:

3

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

+1  A: 

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:

Jon
Something a bit less rubbish would be to just declare the StringBuffer inside the loop.
Mark E
Ah, I think sb.setLength(0); is cleaner and more efficient than declaring it inside the loop. Your solution goes against the performance benefit of using StringBuffer...
Jon
I think the performance benefit comes from the string mutability, not from saving the instantiation. here's a quick test of 1e8 iterations: inside loop (2.97s): http://ideone.com/uyyTL14w, outside loop (2.87s): http://ideone.com/F9lgsIxh
Mark E
I don't think that's a very accurate microbenchmark.
Jon
Speaking of performance: Unless your code is accessed in a multi-threaded scenario, you should use StringBuilder rather than StringBuffer -- see javadoc: "Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations".
netzwerg
i agree with mark , it is better to create the object inside the loop and keep the referance outside....
sreejith
The only benefit of creating the SB outside is not losing the internal (potentially long) char[] of it. If in the first iterator it grew up enough, the second loop will not need to resize any char[]. But for getting the advantage the "clear method" will have to preserve the size of the internal array. setLength does that but it also sets to \u0000 all the not used chars in the SB, so it's less performant that simply creating a new SB with a good initial capacity. Declaring inside the loop is better.
helios
A: 
buf.delete(0,  buf.length());
Suraj Chandran
+2  A: 

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.

Eli Acherkan