Programming tip of the day – Mutable and Immutable

Immutable -> Once a variable has been assigned its value, value cannot be modified in the same memory location.  It allocates a new memory space and then puts the modified contents into that variable.

Mutable -> Variable’s value can be modified in the same memory location.

 

Eg.  String in C# and VB.NET is immutable, StringBuilder is mutable.

String cont = “1”;

cont = cont + ” 2″; //Allocates new memory and adds value ” 2″ inside it

StringBuilder builder = new StringBuilder(“1″);

builder.add(” 2″); //Modifies the value in the same location.

 

 Moral: For strings that require constant change/modification, use StringBuilder (C#) for better performance.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s