If there are two identical string literals in one compilation unit then the code we generate ensures that only one string object is created by the CLR for all instances of that literal within the assembly. This process know as “string interning”
CLR keeps string storage by maintaining a table called the intern pool, which contains a single reference to each unique literal string declared or created programmatically in the program. Hence, an instance of a literal string with a particular value only exists once in the system
Advantage :
Advantage :
- It decreases memory consumption
- It decreases time required to compare two strings
- After declaring new string literal, It needs to search all strings objects in memory to check if any one matches with in assembly
Example 1 :
string str1=”christopher”;
string str2=”christopher”;
Console.WriteLine(str1 == str2); // true
Console.WriteLine(Object.ReferenceEquals(str1,str2); // true
Here both
strings (i.e. str1, str2) are having same identical text/literals. So it creates
only one memory location by CLR and both strings will be pointed to same memory
location (This process known as string intern).
Example 2:
string str1=”christopher nolan”;
string str2=”christopher” + “nolan”;
Console.WriteLine(str1 == str2); // true
Console.WriteLine(Object.ReferenceEquals(str1,str2); // true
Here both
strings (i.e. str1, str2) are having same identical text/literals. So it creates
only one memory location by CLR and both strings will be pointed to same memory
location (This process known as string intern).
Example 3:
string
lastname=”nolan”
string str1=”christopher nolan”;
string str2=”christopher ” + lastname;
Console.WriteLine(str1 == str2); // true
Console.WriteLine(Object.ReferenceEquals(str1,str2); // false
Here second condition
returns false, because we are assigning string object instead of string text/literal.
If we change str2 assignment as follows
string str2=string.Intern(”christopher ” + lastname);
Console.WriteLine(Object.ReferenceEquals(str1,str2); // true
Now it
returns true.
Example 4:
string
str1=”christopher nolan”;
string str2=new
StringBuilder().Append(“Christopher “).Append(“nolan”).ToString();
string str3=String.Intern(str2);
Console.WriteLine((object)str1 == (object)str2);
// false
Console.WriteLine((object)str1 == (object)str3); // true
Here first condition
returns false, because we are assigning string object instead of string text/literal.
Example 5:
string
str1=””;
string str2=””;
StringBuilder sb = new
StringBuilder().Append(String.Empty);
str2 = String.Intern(sb.ToString());
Console.WriteLine((object)str1 == (object)str2);
// sometimes true, sometimes false
Regard to
interning empty string,
.NET
Framework 1.0, 1.1, and 3.5 SP1 returns true
.NET Framework 2.0 SP1, 3.0 returns false
Happy Coding :)
No comments:
Post a Comment