StringBuilder Remove or create a new instance.

I wanted to know if the StringBuilder was faster by removing all the text or creating a new instance everytime. So I created a test winforms application with the following test case and results.

First Case:
Append 100 unique lines of text to a string builder and do this 200.000 times. But every time (200.000 times) create a new instance of the StringBuilder.
Result: 36 seconds

Second Case:
Append 100 unique lines of text to a string builder and do this 200.000 times. But every time (200.000 times) use the Remove method (sb.Remove(0,sb.Length)).
Result: 31 seconds

Is also did the first and second case for 400.000 times and the result was:

First case: 1 min 11 seconds
Second case: 1 min 3 seconds

And to complete the test I also made the test with 200 unique lines of text and in a iteration of 400.000 times. Result was:

First case: 2 min 26 seconds
Second case: 2 min 9 seconds

 

Memory: For memory usage you don't have to do it, in all the cases the memory uses was almost the same. Just a few K more in the first case.

Conclusion: Maybe a useless test because who is gonna create 400.000 a new stringbuilder with 200 lines. But the Remove is a little faster (small 20%).

 

Maybe for the .NET newbees: Don't try this with String concatenation. :-)

- Wesley

Published Friday, October 05, 2007 7:28 AM by wesleyw

Comments

# re: StringBuilder Remove or create a new instance.

Thursday, August 28, 2008 11:23 AM by reo

Thanks for posting this. I was just wondering about it myself.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above:
Powered by Community Server (Non-Commercial Edition), by Telligent Systems