Knowledge Transfer

Monday, December 29, 2008

Difference between StringBuilder and String.Concat method in C#.Net

Hi DotNetGems,

StringBuilder Namespace : System.Text.StringBuilder (Mutable)
String Namespace : System.String (Imutable)

Now Both String.Concat(),Fromat(),join() Methods are Concating the string values to another string value but why C#.Net Introduce the StringBuilder Class???????????
.
.
.
Difference between StringBuilder and String?
Difference between mutable and Immutable?

How String Concatenation String Builder Append affects performance

Most of us have used String concatenation in our projects, Have we ever given a thought to what goes on behind while concatenating the strings?

There is a major flaw in using string concatenation as against the String builders append concerning performance only.
Except for performance and memory management both are same and give us the same desired output.

How they work
Lets take a look at how the things work when we concatenate strings

lets take a case where we are concatenating 2 strings and assigning the output to a 1st string

outputString += secondString;

In the above case, each instance of the string is created and assigned hence

in total we will have 3 instances of the strings!! Surprised?? well thats how strings concatenation works

It will create a new string outputString,with both old outputString and secondString

String objects in .net are immutable. Once the string has been created, the value can’t be changed. When you type
outputString = outputString + secondString;
you actually discard the old outputString and create a new string object containing the result of the concatenation. When repeated several times, you end up constructing many temporary string objects.

now just imagine the case where you have n number of strings you have to concatenate how many string objects will be created wont that be a waste of time ??? Creating a string object assigning it some value then again creating a string object and so on …..

Imagine the impact on the performance of the application!!!!

Now lets see how String builder works

Using a string builder you will have


System.Text.StringBuilder outputString = new System.Text.StringBuilder();

outputString.Append(secondString);

StringBuilder, is a mutable string hence in this case we just have 1 instance of outputString and the second string is appended into that existing instance
no other instance is created hence the process is efficient and fast.

Note :- The point to remember here is that using StringBuilder for a concatenation of 2-3 strings doesnt make a significant difference in the performance but when you have numerous strings then the usage of StringBuilder has a big positive Impact on the performance

Labels: , , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]



<< Home