Friday, January 9, 2009

Difference between Mutable and Immutable

Let me first explain the general meaning of Mutable and Immutable.

Mutable: Capable of or tending to change in form or quality or nature

ImMutable: Not subject or susceptible to change or variation in form or quality or nature

the same thing in terms of .NET

ImMutable: String is a ImMutable Object. Whenever you refer string in your code, it will create a new object in memory. Means, a new memory location will be occupied to that string.

for Example: str1 = str1 + str2.

this operation require 3 memory locations not 2

Mutable: Sytem.Text.StringBuilder is Mutable Object. when you append string to string builder, or alter it's text, it will always use the single memory location. This is very important when you need to work on a large set of string operation.

Note: always use StringBuilder whenever the operation involve large set of string operations, there will be a big difference in performance if you'll use string instead.

1 comment: