How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?
-
2Another 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 09:09
10 Answers
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:

- 62,090
- 32
- 125
- 150
-
16Something a bit less rubbish would be to just declare the StringBuffer inside the loop. – Mark Elliot Feb 11 '10 at 05:33
-
12Ah, 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... – Jonathan Holloway Feb 11 '10 at 05:38
-
6I 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 Elliot Feb 11 '10 at 05:46
-
6Speaking 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". – Rahel Lüthy Feb 11 '10 at 07:53
-
i agree with mark , it is better to create the object inside the loop and keep the referance outside.... – sreejith Feb 11 '10 at 08:51
-
4The 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 09:08
-
Declaring inside the loop doesn't work if what you're doing is accumulating a value across iterations of the loop. For example: `Map
map; StringBuffer buffer = new StringBuffer(); for (String arg : args) { if (arg ...) { buffer.append(arg); } else if (arg ...) { map.put(arg, buffer.toString()); // Clear the buffer here. }` You can _recreate_ the buffer where you need it cleared, but the buffer can't be fully contained within the loop or it's besides the point. – Spanky Quigman Jun 29 '11 at 20:11 -
2
-
2
-
Looking at the code of StringBuilder, setLength clears the buffer (but it uses Arrays.fill which is very fast) whereas delete doesn't, but it does try to do an Array copy of zero bytes. – rghome Dec 04 '18 at 09:59
-
The right approach depends upon what you are trying to achieve. For code clarity, use a buffer defined in the loop and be done with it. If you are trying to limit memory usage as much as possible, either define the buffer in the loop and let GC handle it or use `setLength(0)` which will discard the internal `char[]` each time. If you are looking for as little garbage as possible, you have to use `delete(0,length)`. Just remember that using `delete(0,length)` means that the buffer can get really really big. If the loop runs for a long time, that big buffer doesn't get any smaller. – Christopher Schultz May 26 '23 at 18:49
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

- 3,742
- 4
- 31
- 50

- 897
- 9
- 13
-
2@MMahmoud, In the code example it should read `setLength` instead of `setlength`. – OnaBai Dec 07 '12 at 15:58
-
When I see setLength code source, how is it working (https://gist.github.com/ebuildy/e91ac6af2ff8a6b1821d18abf2f8c9e1) here count will be always greater than newLength (0) ? – Thomas Decaux Nov 02 '18 at 19:20
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.

- 2,343
- 1
- 23
- 42
public void clear(StringBuilder s) {
s.setLength(0);
}
Usage:
StringBuilder v = new StringBuilder();
clear(v);
for readability, I think this is the best solution.

- 279
- 3
- 5
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.

- 6,401
- 2
- 27
- 34
-
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 08:20
-
2If 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
-
1It'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
-
1I agree that in some cases, code readability is more important than performance, but in this case, it's only one line of code! And you can run a benchmark which will prove you that allocation and object creation, plus garbage collecting is more expensive than not doing it at all. As we are in a loop, it is more than relevant. – Louis CAD Nov 26 '15 at 14:17
-
There's no single "this case"; the constraints, requirements and considerations for "this case" for DB-constrained server-side code are different from "this case" for a realtime system, which is again different from "this case" for an Android application. I never said that there's no performance difference, I said that it's usually negligible (i.e. your performance is dominated by other factors). From my personal experience, readability is _usually_ more important than performance (to a sane degree), but the bottom line is that each developer will decide on the tradeoff for themselves. – Eli Acherkan Nov 26 '15 at 15:32
-
Small overheads, like unneeded allocation, garbage collecting (which may freeze your app while running, dropping frames), etc, are the small performances issues which, with other apps and other places, lead to poor battery life, poor performance, poor UX, and accumulated with others, a big overhead. #PerfsMatters – Louis CAD Nov 26 '15 at 15:41
-
To each his own. I mostly subscribe to Knuth's view of premature optimization being the root of all evil. I think I'd really enjoy using an Android app where the overall performance is so great that it's seriously affected by initializing StringBuffers in a loop. – Eli Acherkan Nov 26 '15 at 15:46
-
1I also subscribed to Knuth's view, but his point of view is not always true. Adding **just one line** to potentially gain CPU cycles and memory is absolutely not evil. You are taking the idea too straight. Note that a loop is usually repeated many times. A loop can be repeated thousands of times, which can eat precious megabytes on a mobile (and also on server or computer) if not optimized carefully. – Louis CAD Nov 26 '15 at 15:52
-
1I 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
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

- 51
- 1
- 5
StringBuffer sb = new SringBuffer();
// do something wiht it
sb = new StringBuffer();
i think this code is faster.

- 35
- 1
-
3This will have performance issues. It creates a new object after every iteration – Aditya Singh Jun 19 '15 at 14:34
-
@AdityaSingh It's a perfectly reasonable approach. Don't assume performance problems without evidence. – shmosel Jan 16 '18 at 23:23
-
1Assuming things based on an understanding of what is going on is the basis of intelligence. – rghome Dec 04 '18 at 09:56
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);
}

- 426
- 6
- 15
I think the best way to clear StringBuilder
is Clear()
method.
StringBuilder sb = new StringBuilder();
sb.Clear();
Note: Its work only in .net

- 3,465
- 2
- 20
- 27
-
1
-
This only work in .net https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder.clear?view=net-6.0 – M2012 Mar 09 '22 at 21:01