Of late, I am refactoring a lot of code and one such code I found out was to append string
s 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 string
s 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 string
s 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:
- 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