string and string builder

For a simple string concantenation code shown below it will create 3 copies of string in memory.

//The below line of code Creates one copy of the string
string str = “shiv”;

/* The below line of code creates three copies of string object one for the concatenation at right hand side and the other for new value at the left hand side. The first old allocated memory is sent for garbage collection.*/
str = str + “shiv”;

When you use the string builder for concatenation it will create only one copy of the object.

/* The below code uses string builder and only one
object is created as compared to normal string where we have 3 copies created*/
StringBuilder objBuilder = new StringBuilder();
objBuilder.Append(“shiv”);

Ok now summarizing what should we say to the interviewer.

String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable , in other words the same object will changed rather than creating new objects.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s