Friday 21 September 2012

Difference between string and stringbuilder in c#

String is immutable(Non updatable). It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string

StringBuilder is mutable(Updatable). It can be modified in any way and it doesn't require creation of new instance. When work is done, ToString() can be called to get the string.

Simple example: 










You'll end up creating 2001 strings here, 2000 of which are thrown away. The same example using StringBuilder:











This should place much less stress on the memory allocator.

the final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.

if you make a lot of string operations like appending,truncating then StringBuilder is a good option.

No comments:

Post a Comment