New Message on dotNET User Group Hyd

StringBuilder OR String Concat?

Reply
  Reply to Sender   Recommend Message 3 in Discussion
From: Vishnu-Chivukula

Hi Dharmesh,
 
A great brain teaser. If you are concatenating only once, sting concat is faster than String builder.
 
This is because, when you concat a string to another string, you are creating a 3rd string. A = A + B doesn't replace the original A, it actually leaves the original A and produces a C to hold the value of A + B. So for each String.Concat, you are producing a whole new value on the heap. This is because a String is immutable. (Its value cannot be modified once it has been created).
 
Where as a String Builder represents a string-like object whose value is a mutable. The methods that modify an instance of this class return a reference to that same instance.
 
But what if we run the concatination in a loop, say about 10,000 times or more. Still the String.Concat should be efficient. The answer is NO. This is where the Garbage Collector comes into picture. So each time the String.Concat runs in the loop a new string is created and the other existing strings are left unreferrenced, Which can be collected by Garbage collector. These unreferrenced string objects occupy a hugh chunck of memory in the heap. This forces the Garbage collector to run and collect the unreferrenced objects. More number of times the GC runs, the slower the performance.
 
The String builder uses local buffre that expands when data is added to it. Since its still one single huge object in memory, the GC wont collect it. In this case the StringBuilder class is more efficient that String.Concat.

For more information on this and statistics on performance check this out...
http://dotnetjunkies.com/WebLog/rlewallen/archive/2004/12/02/34739.aspx

Great one, Dharmesh.
 

Happy Coding

View other groups in this category.


Also on MSN:
Start Chatting | Listen to Music | House & Home | Try Online Dating | Daily Horoscopes

To stop getting this e-mail, or change how often it arrives, go to your E-mail Settings.

Need help? If you've forgotten your password, please go to Passport Member Services.
For other questions or feedback, go to our Contact Us page.

If you do not want to receive future e-mail from this MSN group, or if you received this message by mistake, please click the "Remove" link below. On the pre-addressed e-mail message that opens, simply click "Send". Your e-mail address will be deleted from this group's mailing list.
Remove my e-mail address from dotNET User Group Hyd.

Reply via email to