Click here to Skip to main content
15,888,521 members
Articles / All Topics

Better Approach to Clearing StringBuilder TIP

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
7 Nov 2011LGPL32 min read 11.4K   3
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).

C#
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:

C#
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:

  • TestMethod1: 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)


Written By
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/

Comments and Discussions

 
GeneralMy vote of 3 Pin
AlbertoLeon CSharpMan6-Nov-11 22:04
AlbertoLeon CSharpMan6-Nov-11 22:04 
I wask working for years using extensive use of StringBuilder, is a good way .Leng=0

Thanks! Please revise the article to use the CAMEL notation, no write the classes' name lowercase!
QuestionStringBuilder.Clear... Pin
Sander Rossel6-Nov-11 11:29
professionalSander Rossel6-Nov-11 11:29 
AnswerRe: StringBuilder.Clear... Pin
zenwalker19856-Nov-11 15:04
zenwalker19856-Nov-11 15:04 

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

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