Tuesday 1 April 2014

String Pooling in .net C#

The string intern pool is a table that contains a single reference to each unique literal string declared or created programmatically in your application. The Common Language Runtime (CLR) uses the intern pool to minimize string storage requirements. As a result, an instance of a literal string with a particular value only exists once in the system.

e.g :  If you assign the same literal string to several different variables, at runtime, the CLR retrieves the unique reference to that literal string from the intern pool and assigns it to each variable.

1. string x = "ab";
2. String y = "ab";

In the above case when the variable ‘y’ is assigned a value, the CLR first checks it in the string Pool for an object with the same value, if such a variables exists in the Pool, the reference to the same object is assigned to the variable ‘y’.

To confirm if the same reference has been assigned we can check for the HashCode for both the string object, and they come out to be same,

1.   Console.WriteLine(x.GetHashCode());
2.   Console.WriteLine(y.GetHashCode());
3.   




What happens when you concatenate two strings?

Even if you Concatenate two strings and the output string is in the pool it will reference the same string.


Also optionally, if a variable is assigned value using “string.intern() “ method in C#, the string value is implicitly placed in the pool maintained by .net for string optimization.  However, as of .NET 2.0 and later, there is essentially no difference. The JIT will end up referencing the same object on the heap anyhow.

According to the C# specification, section 2.4.4.5:



About Author:
Santosh Saroj is consultant in Systems Plus Pvt. Ltd and keen to resolve challenges using his technical skills. He actively contributes to technology and can be contacted at: santosh.s@spluspl.com

2 comments: