Monday, May 16, 2011

String V/s Stringbulder


In 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 sandeep chaurasia ”;
str += “and i am”; str += “working on “;
str += “Post of “;
str += “difference between string and string builder”;
Response.Write(str);
and the expected output well you probably guessed it right
“My Name is sandeep chaurasia and 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 sandeep”);
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 sandeepand 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.Happy coding.

No comments:

Post a Comment