Friday, October 23, 2009

string literal, System.String class and StringBuilder in .NET

In .NET, you can declare a string variable using string literal or System.String. The main difference between is that, string literal is mutable and System.String is immutable.

(i.e.)

string value1 = "hello";
string value2 = "hello";

Both of these variables will share the same object in memory.
But,

System.String value1 = "hello";
System.String value2 = "hello";

Two objects will be created in memory though the values are same.

The same will be case with StringBuilder and String.Concat() also;

StringBuilder stringBuilder1 = new StringBuilder();
stringBuilder1.Append("hello");

StringBuilder stringBuilder2 = new StringBuilder();
stringBuilder2.Append("hello");

string sb1 = stringBuilder1.ToString();
string sb2 = stringBuilder2.ToString();

Two objects will be created in memory.

string concat1 = String.Concat("hello", " ", "world");
string concat2 = String.Concat("hello", " ", "world");

Two objects will be created in memory.

Why this behavior is that, string literal uses "string Interning" concept. .NET framework internally maintains "Intern Pool" for string values to avoid huge amount of duplicate string data.

System.String, StringBuilder and String.Concat() creates immutable string objects. Also, .NET framework has String.Intern() method which enables the identical string objects to share the same object.

string interned1 = String.Intern(String.Concat("hello", " ", "world"));
string interned2 = String.Intern(String.Concat("hello", " ", "world"));

1 comment:

  1. Rajavel,

    string and System.String are identical according to http://msdn.microsoft.com/en-us/library/362314fe.aspx

    so both are Immutable!
    Also, when you change a literal string, you'll get a new string object.

    ReplyDelete