Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Better Approach to Clearing StringBuilder TIP

, 7 Nov 2011 LGPL3
Rate this:
Please Sign up or sign in to vote.
Better Approach to Clearing StringBuilder TIP

Of late, I am refactoring a lot of code and one such code I found out was to append strings in a loop where its iteration count is pretty much unknown. In fact, I have seen a lot of code elsewhere too wherein many developers use stringbuilder to append strings before even knowing if it’s really required in that code chunk part. So in case you have a doubt when to choose what (string vs StringBuilder), then you must read Jon Skeets article.

So I saw this code chunk today in a foreach loop and I started to wonder why people write such code, let me show you the code I am talking about, which looks visibly flawless but carefully understood reveals the problem: (Yes, the below code has constant string appending statements, but my actual code has variable numbers of strings to be appended).

for (int i = 0; i < 100000; i++)
{
StringBuilder sb = new StringBuilder();

sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);

var x = sb.ToString();
}

To look at the above code, it looks fine atleast for visibility sake. Now many people follow this style because on every loop start, they need a fresh SB instance so that they can append and do some operations on it. So many developers think of clearing SB items you need to create new instances in the loop.

But there is another very simple way, which you may already know about. In case you did not, just set the length property of SB to 0, that way the SB contents gets emptied and you can start appending again as if the SB is instantiated freshly. The major benefits of doing this way is performance in creating object on heap. Since we all know that heap object creation is really a pain for CLR, I changed the above code a bit and it looks like this:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
sb.Length = 0;
sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);
sb.Append(“ada”);

var x = sb.ToString();
}

Now this way, I am not creating a new object on heap and on every loop start, I do get an empty SB so I can start filling it fresh.

To back up my words, I did a bit of performance analysis on the below code:

As per this code, I got these results as shown below:

  • TestMethod 1: Ticks = 472683843 Millisecond =157
  • TestMethod2 : Ticks = 941050287 Millisecond =314

So the output shows that resetting the length property value is far better than having new SB objects created every time.

Hope it helps, your comments are welcome.

Thanks. :)


Filed under: c#, CodeProject, dotnet Tagged: .NET, blog, c#, codeproject, dotnet, tips

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)

Share

About the Author

zenwalker1985
Software Developer (Senior) Siemens
India India
A .net developer since 4+ years, wild, curious and adventurous nerd.
 
Loves Trekking/Hiking, animals and nature.
 
A FOSS/Linux maniac by default Wink | ;)
 
An MVP aspirant and loves blogging -> https://adventurouszen.wordpress.com/
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 Pinmemberalbertoleon6-Nov-11 23:04 
QuestionStringBuilder.Clear... PinmemberNaerling6-Nov-11 12:29 
AnswerRe: StringBuilder.Clear... Pinmemberzenwalker19856-Nov-11 16:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150305.1 | Last Updated 7 Nov 2011
Article Copyright 2011 by zenwalker1985
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid