Wednesday, October 31, 2007

Mutable or Immutable? (String and StringBuilder)

Mutable or Immutable? (String and StringBuilder)

An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification. Developers are modifying strings all the time in their code. This may appear to the developer as mutable - but it is not. What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value. For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.

Why string? Can't use StringBinder everywhere?

No. You can't. When initializing a StringBuilder you are going down in performance. Also many actions that you do with string can't be done with StringBinder. Actually it is used mostly for situations as explained above. Last week I show a person, who used StringBuilder to just add two strings together! its really nonsense. We must really think about the overhead of initialization. In my personal experience a StringBuilder can be used where more than four or more string concatenation take place. Also if you try to do some other manipulation (Like removing a part from the string, replacing a part in the string, etc, etc) then better not to use StringBuilder at those places. Because anyway we are creating new strings. Another important issue. We must be careful to guess the size of StringBuilder . If the size which we are going to get is more than what assigned, it must increase the size. Which will reduce the performance of it.
History