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

share|improve this question
1  
Another question: why do you use a SB only for one iteration of the loop? Is there another inner iteration? SB is not worthy if you simply want to do A+B+C+D (Java compiler will internally use a SB). It helps if you want to conditionally add parts of strings, but otherwise... simply use "+". – helios Feb 11 '10 at 9:09
    
duplicate:stackoverflow.com/questions/5192512/… – Natan Cox Oct 11 '12 at 9:50

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:

share|improve this answer
10  
Something a bit less rubbish would be to just declare the StringBuffer inside the loop. – Mark Elliot Feb 11 '10 at 5:33
6  
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 Feb 11 '10 at 5:38
4  
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): ideone.com/uyyTL14w, outside loop (2.87s): ideone.com/F9lgsIxh – Mark Elliot Feb 11 '10 at 5:46
4  
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 Feb 11 '10 at 7:53
3  
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 Feb 11 '10 at 9:08

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
share|improve this answer
2  
@MMahmoud, In the code example it should read setLength instead of setlength. – OnaBai Dec 7 '12 at 15:58

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.

share|improve this answer

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.

share|improve this answer
    
As java is now mostly used on Android, I'm not sure allocating a new object in a loop is a good practice for performance and battery life. The code complexity added by clearing the StringBuilder is minimal versus the potential performance gain. – Louis CAD Nov 26 '15 at 8:20
1  
If you have any evidence of such performance difference, please share it. (I'll be also glad to see statistics of where Java is mostly used, and under which definition of "mostly".) – Eli Acherkan Nov 26 '15 at 11:07
    
It's well known that allocation (new keyword in Java) is more expensive than just changing some fields of the same object. For "mostly", which you could replave with highly, there's more than 1.5Billion of Android Devices, all using Java. – Louis CAD Nov 26 '15 at 11:17
    
Claims of "potential performance gain" are best backed up by concrete evidence, such as benchmarking of this specific case. Then, depending on the requirements and on the application, each developer can make their decision in the tradeoff between performance and code readability. – Eli Acherkan Nov 26 '15 at 14:10
1  
I think we both stated our viewpoints clearly enough, and I feel that further discussion will not be beneficial to this comments section. If you feel that my answer is incorrect, misleading or incomplete, then you - or anyone - are by all means welcome to edit and/or downvote it. – Eli Acherkan Nov 26 '15 at 16:01
buf.delete(0,  buf.length());
share|improve this answer

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

share|improve this answer
StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();

i think this code is faster.

share|improve this answer
2  
This will have performance issues. It creates a new object after every iteration – Aditya Singh Jun 19 '15 at 14:34

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.