How do you clear the string buffer in Java after a loop so the next iteration uses a clear string buffer?
|
One option is to use the delete method as follows:
Another option (bit cleaner) uses setLength(int len):
See Javadoc for more info: |
|||||||||||||||||||||
|
The easiest way to reuse the
You may have the case like
|
|||||
|
You have two options: Either use:
Or use:
NOTEAvoid declaring |
|||
|
I suggest creating a new |
|||||||||||||||||||||
|
|
|||
|
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
Very simple benchmark (I just manually changed the code and do different test ):
} 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 |
|||
|
i think this code is faster. |
|||||
|