Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

C# Code Optimization Using StringBuilder

DZone's Guide to

C# Code Optimization Using StringBuilder

There are some cases where we can optimize our code by using StringBuilder instead of string. Let me show you what I mean.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Using StringBuilder Wisely

We can optimize our code in some cases by using StringBuilder instead of string. So, what’s the situation where StringBuilder is more efficient than string, I will explain this to you with an example. Consider a case when you are concatenating a string in the same variable continuously in a loop and after the end of the loop you have to use that final value—here you should use StringBuilder’s append method to concatenate, not string variable. Another question is how does code execute fast from using StringBuilder—it’s because of the internal working of these two.

How String Works 

Each time we concatenate a string, it creates a new object in memory then copies an old value of the string in a new object, putting new values in that object then pointing our string variable to the newly created object.

How StringBuilder Works 

Each time we append a string, we put the new value of the string in the same memory object. We don't create a new object each time, nor do we copy old values to a new object each time.

Now you can clearly understand why StringBuilder is more efficient in the above scenario.

I will show you some sample code which you can run as a console application to see the difference in speed of the execution of a string versus StringBuilder by yourself.

The timing of the outputs of the code will be something like this:

Using String concatenation: 31939 milliseconds
Using StringBuilder: 27 milliseconds

Sample Code

System.Diagnostics.Stopwatch time = new Stopwatch();
string test = string.Empty;
time.Start();
for (int i = 0; i < 100000; i++)
{
    test += i;
}
time.Stop();
System.Console.WriteLine("Using String contactenation: " + time.ElapsedMilliseconds + " milliseconds");
StringBuilder test1 new StringBuilder();
time.Reset();
time.Start();
for (int i = 0; i < 100000; i++)
{
    test1.Append(i);
}
time.Stop();
System.Console.WriteLine("Using StringBuilder: " + time.ElapsedMilliseconds + " milliseconds");

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
c# ,c# developer ,c#.net ,programming practices ,code analysis ,optimization

Published at DZone with permission of Nouman Khan. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}