What is the difference between Strings and StringBuilder in C# .NET ?

Short Answer : String is immutable – whereas StringBuilder is mutable.

What does that mean ?

Wiki says : In object-oriented, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.

From the StringBuilder Class documentation:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object.

In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

Now keeping all these facts in mind, I tried out the following piece of code and I was very suprised at the results.

Code :

Stopwatch stopwatch = new Stopwatch();

// Bad Code  
stopwatch.Start();  
string str1 = "";  
for (int i = 0; i < 100000; i++)  
{  
str1 += i;  
}  
stopwatch.Stop();  
Console.WriteLine("Time taken using string : " + stopwatch.Elapsed.Seconds + "seconds" );

stopwatch.Reset();

// Good Code  
stopwatch.Start();  
StringBuilder builder = new StringBuilder();  
for (int i = 0; i < 100000; i++)  
{  
builder.Append(i);  
}  
string str2 = builder.ToString();  
stopwatch.Stop();  
Console.WriteLine("Time taken using string : " + stopwatch.Elapsed.Seconds + "seconds");

Output:

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at “mail@yassershaikh.com” and I’ll get back to you as soon as possible.

Cheers !

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>