Monday, 19 September 2011

What is the Main difference between String and StringBuilder and why do we use StringBuilder.

n Dot Net there will be many cases where in we need to operate on strings and first thing we remember is using system.String but there are certainly many points we need to remember and consider before we operate on strings.
1) Performance.
2)how many times we need to concatenate.
Lets take an example for concatenate five strings.
EX 1. Using System.String
System.String str =“My Name is roja”;
str += “and i am”; str += “working on “;
str += “Post of “;
str += “difference between string and string builder”;
and the expected output well you probably guessed it right
“My Name is rojaand i amworking on Post of difference between string and string builder”
Now what has happed? yes the important question now how many times we have appended the str variable those number of times string was created in memory location and abandoned when a new string is created and later waiting for garbage collection.
This leads to memory wastage and degradation of performance because string are immutable(that means any change to string causes a runtime to create a new string and abandon old one).
Think about the situation where in u need to work on 100 or more strings????
Dot Net has answer for it in the form of System.Text.StringBuilder class
EX2. Same Example using StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append( “My Name is roja”);
sb.Append( “and i am”);
sb.Append( “working on “);
sb.Append( “Post of “);
sb.Append( “difference between string and string builder”);
and the output is same as previous
“My Name is rojaand i amworking on Post of difference between string and string builder”
But this time there was only one string created in memory dynamically and modified as we append the new string, by this there is not much garbage collection and also helps improve performance. Append is taken only for example there are a lot of other functions which are just waiting for you to invoke.

Both String and String Builder are classes use to handle Strings.

The most common operation with a string is Concatenation. When we use string object to concatenate two strings, the first string is combined with the new string by creating a new object in the memory as string object, and the old string object is deleted. So String is also called immutable. 

If we use String builder object and use Append method ,the concatenation is done in the existing string. String builder is also called mutable.

So operation on string builder is faster than the string object.
String builder is more efficient in case large amount of string operations have to be perform.