String Interning in .net

Friday, July 1, 2011

We all know that the way .net handles a string is not optimal and uses  up lot of memory,  thought there are reason to do like this. But if we have more string objects or comparison inside our assembly then in this case surely it is going to be a performance hit. But here what really happens is framework itself take cares at least some part of it using the concept of Sting Interning.

So what is String interning in Microsoft .net. How does it helps the C# code Execution..

It seems that there is an internal hashtable maintained with the actual string value and it’s reference to managed heap.  And two methods help us to handle this hash table

This is the “Intern” and “IsInterned” methods which is part of string manipulation class.

By default when an assembly is loaded all common used strings in the assembly (including manifest and metadata) are interned and stored to this hash table . And whenever this is needed , “IsInterned” finds out whether it is already interned and if not the first method interns it, thereby ensuring  that string objects are not duplicated due to it’s immutability while doing a comparison to get the exact string we need. (“IsInterned” sends the hashed value to fetch from the internal hashtable )

To simply for your better understanding let us see the below example

string str1 = test;
string str2 = test;
object.ReferenceEquals(str1 ,str1);

object.ReferenceEquals(String.Intern(str1), 
            String.Intern(str2));

In the above example statement line number 3 returns false, while the next stament returns true thought we are using the exactly same statement. Once a string is interned, the internal hash table stores reference of that string. and whenever that string is needed again "IsInterned" method takes the string as argument and  fetch the actual reference for that string from the above said internal hashTable

This procedure seems to be widely used to parse the metadata and manifest of the assembly, otherwise obviously there should be a performance hit when we use reflection.

But the other pointed noted here is that frequent hashing and lookup  could also cause a performance hit when it is not really required so there is a way to control this too by applying the “CompilerRelaxationattribute” with “NostringInterning”. But this is again changeable by the compiler if decides that the more better way to go will be with string interning.


Was this post helpful to you ? !!.. Then please like this in any of the social media below !.
Let it be useful for others too..

kick it on DotNetKicks.com
Filed Under: .Net, .Net C# learning, C#



Also Read >>> Some reference about state management in ASP.Net To Receive full blog post and updates to your inbox. Click Here and enter your email address

blog comments powered by Disqus
Click here and Follow us on Twitter