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
2010-02-11 05:30:03
Something a bit less rubbish would be to just declare the StringBuffer inside the loop.
Mark E
2010-02-11 05:33:49
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
2010-02-11 05:38:19
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
2010-02-11 05:46:42
I don't think that's a very accurate microbenchmark.
Jon
2010-02-11 06:43:10
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
2010-02-11 07:53:10
i agree with mark , it is better to create the object inside the loop and keep the referance outside....
sreejith
2010-02-11 08:51:21
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
2010-02-11 09:08:27
+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
2010-02-11 08:51:36