content top

StringBuilder Vs String Concatenations

StringBuilder or String Concatenation.. Is there any real performance issue in string concatenation ? When should I use StringBuilder ? To answer these questions, first lets examine the difference between String and StringBuilder classes.

What is the difference between String and

StringBuilder?

String is immutable while StringBuilder is mutable.

After a string object is created its value cannot be changed. Then how the following is possible ?

String name = “Mr. “;

name = name + “First Name” + “Last Name”;

When the concatenation operation is performed the actual string object is discarded and a new string object is created.

But StringBuilder is mutable. StringBuilder class provides methods to change its contents at anytime. StringBuilder class has a very useful method “append” to add new strings to the end of the existing string value. StringBuilder internally reserves a certain amount of memory(Buffer). When a new string is added to the StringBuilder object, the new string is copied to the existing buffer. If the buffer is not enough to fit the new string , then a new buffer is created to fit the new string.

A Performance Test ( StringBuilder VS Concatenation):

Here is a simple performance test which demonstrates the power of StringBuilder over string concatenation.

DateTime start;

StringBuilder strBuilder = new StringBuilder();
string str = string.Empty;

TimeSpan strBuilderExTime = new TimeSpan();

start = DateTime.Now;
for (int i = 0; i < 80000; i++)
{
str = str + “Test string”;
}
strBuilderExTime = DateTime.Now - start;
Console.WriteLine(”Exection Time for string concatenation =” + strBuilderExTime.ToString());

start = DateTime.Now;
for (int i = 0; i < 80000; i++)
{
strBuilder.Append(”Test string”);
}
strBuilderExTime = DateTime.Now - start;
Console.WriteLine(”Exection Time for string builder oncatenation =” + strBuilderExTime.ToString());

Output :

Exection Time for string concatenation = 00:02:37.9687500
Exection Time for string builder oncatenation = 00:00:00.0156250

You can see a very huge time difference between the above two.

When should i use StringBuilder ?

Is StringBuilder always a better Option than concatenation? No… If there are only few concatenations (say less than 5 apprx.) , then no need to go for StringBuilder.

Conclusion:

If the number of concatenations is more, then use StringBuilder. But if the number of concatenations is very few then go for ordinary “+” concatenations.

Blog Widget by LinkWithin

1 Comment »

  1. avatar comment-top

    With String.Concat optimizing up to 4 appendages per statement, i thought += would be optimized as well.

    comment-bottom

RSS feed for comments on this post. TrackBack URL

Leave a comment