DotNet

String Pooling in DotNet


 

When compiling source code, your compiler must process each literal string and emit the string into the managed module’s metadata. If the same literal string appears several times in your source code, emitting all of these strings into the metadata will bloat the size of the resulting file.To remove this bloat, many compilers (include the C# compiler) write the literal string into the module’s metadata only once. All code that references the string will be modified to refer to the one string in the metadata. This ability of a compiler to merge multiple occurrences of a single string into a single instance can reduce the size of a module substantially. This process is nothing new—C/C++ compilers have been doing it for years. (Microsoft’s C/C++ compiler calls this string pooling.) Even so, string pooling is another way to improve the performance of strings and just one more piece of knowledge that you should have in your repertoire.

CLR automatically does string pooling by maintaining internpool table in assembly metadata but sometimes we need to do it manually using Intern method of string class.

The Intern method uses the intern pool to search for a string equal to the value of any string. If such a string exists, its reference in the intern pool is returned. If the string does not exist, a reference to string is added to the intern pool, then that reference is returned.

Below is code for this:

  
String s1 = “Neeraj Kaushik”;
String s2 =new StringBuilder().Append(“Neeraj”).Append(” Kaushik”).ToString();
String s3 = String.Intern(s2);
Console.WriteLine(“s1 == ‘{0}’”, s1);
Console.WriteLine(“s2 == ‘{0}’”, s2);
Console.WriteLine(“s3 == ‘{0}’”, s3);
Console.WriteLine(“Is s2 the same reference as s1?: {0}”, (Object)s2 == (Object)s1);
Console.WriteLine(“Is s3 the same reference as s1?: {0}”, (Object)s3 == (Object)s1);

Output:


s1 == ‘Neeraj Kaushik’

s2 == ‘Neeraj Kaushik’

s3 == ‘Neeraj Kaushik’

Is s2 the same reference as s1?: False

Is s3 the same reference as s1?: True

In this case a new string created StringBuilder create new instance of string that is not having same reference with S1. So when we intern value of s2 to s3 then s3 and s1 will share same reference.

In automatic case if assign same value to string instances it will refer to same memory reference like below

  
string a =”neeraj”;
string b= “neeraj”;
bool res= a==b;

Output:

true.

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 )

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