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:

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>