Monday, March 12, 2012

what is the Diff between String and StringBuilder..!

hi all,
pls let me know regarding to String and StringBuilder in c# pls..
thanks in advance
ramnaaMSee
http://www.heikniemi.net/hc/archives/000124.html
http://winfx.msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/T_System_Text_StringBuilder.asp

String is a special class type that is immutable. This means that if you can't actually modify the string value you can only create new strings. So
string s1 = string.Empty;
for( int i = 0; i < 100000; i++ )
{
s1 += i.ToString();
}
s1 doesn't get modified, but a new string gets created and s1 now references the new string. When you are concatenating a lot of string values this is very processor intensive and can have significant performance implications.
StringBuilder is mutable, which means that if you can modify this object.
So you can do
System.Text.StringBuilder sb = new StringBuilder();
for( int i = 0; i < 100000; i++ )
{
sb.Append( i.ToString() )
}
Put some timers around these code samples and see the benefit of StringBuilder.
But for simple stuff like
string s1 = "test"
string s2 = " add some more text";
s1 += s2;
string builder will give you no performance benefit.
Now there are heaps of articles that give you more information. Remember google is your friend
http://www.google.co.uk/search?hl=en&q=string+vs+stringbuilder&meta=

Here are a couple of the results
http://channel9.msdn.com/ShowPost.aspx?PostID=14932
http://www.codeproject.com/Purgatory/string.asp

0 comments:

Post a Comment