a blog for those who code

Tuesday, 15 July 2014

What is String.Intern?

When we use strings in C#, the CLR does string interning internally. Its a way of storing one copy of any string. It comes handy when we have million string of same value, so we dont have to waste so much memory storing the same string over and over again.

CLR maintains a table called the intern pool which contains a single, unique reference to every literal string which is either declared or created programmatically. We have two methods to interact with intern pool, they are String.Intern() and String.IsInterned().

String.Intern(string1) - It retrieves the system's reference to the specified string (string1). It will return the refernce to string1 if it is interned otherwise a new reference to a string with the value of string1. It will give "ArgumentNullException" exception is str is null.

For example.

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

string str1 = "helloworld";
string str2 = new StringBuilder().Appen("hello").Append("world").ToString();
string str3 = String.Intern(str2);

(Object)str2 == (Object)str1 // Different References

(Object)str3 == (Object)str1 // Same Reference

str1 has a value "helloworld" is already interend as it is a literal in the program. StringBuilder() class generated a new string object that has the same value as str1, a reference to that string is assigned to str2. Now String.Intern(str2) searches the reference of "helloworld" in intern pool and returned the reference of str1.

The reference of str1 and str2 is different because they refer to different objects, reference of str1 and str3 is equal because they refer to the same string.

The use of String.IsInterned() is to check if a string is in the intern pool or not. We can pass a reference of a string object to String.IsInterned(), if that string is in the intern pool, it returns a reference to the interned string otherwise it will return null.

Please Like and Share the Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

CC License