System.String Or StringBuilder

Many of us know that we should use StringBuilder object instead of String while building strings when the content of the string variable is unknown at the time of coding. Some of us may not know the real reason behind this guidance other than the high-level fact that StringBuilder is more optimized. Here is the fact, if you are interested.

The System.String class is immutable which means that the value cannot be changed once assigned. Every time you assign a value to a string variable, .NET allocates a new memory location and stores the value. Consider the following snippet of code. The .NET Framework would allocate memory for the variable four times. At the end of the fourth assignment, only the fourth allocation will have the reference. The previous three would be discarded and collected later by garbage collector. If the number of allocations is more, so will be the number of times an allocation is discarded. StringBuilder, on the other hand, is mutable and does not follow this approach to allocating space for strings.


string s;

s ="This ";

s += "is the first ";

s += "sentence in the line. ";

s += "The sentence was formed using multiple assignment statements.";



No comments:


Powered by Blogger.