Go to home page mail me! RSS Feed
FoxMetrics Web Analytics

String Internship

Tuesday, November 11, 2008 5:15 PM

Ok, not internship but intern, this is a brief post about string interning. Within the String namespace you will find the Intern and IsInterned methods. I've always been curious about what they do or why they are there, they are one of those things that you may never use in your whole development career. In the .Net Framework there are 3 types of functions & classes, 1. ones that you just have to use, 2. others that you use because you really need to, 3. and those that you use because you like to write complex stuff - this applies to designs too.

Ok, back to interning, the term string interning in the development world simply means storing only a single copy of a unique string value, this helps with space and code efficiency. Usually these unique strings are stored in a "database" per say known as the string intern pool. Lets get down to code...remember String is a reference type and its immutable.

 

string x = "Rydal";
string y = "Williams";
string z = "Rydal";
 
// since x has the same value as z then they should be the same
Console.WriteLine(Object.ReferenceEquals(x,z));
 
// does it really contain the same value
Console.WriteLine(Object.ReferenceEquals("Rydal", z));
 
// the 'name' string is constructed at runtime, therefore its 
// not interned, so it shouldn't be the same reference
string name = x + " " + y;
Console.WriteLine(Object.ReferenceEquals("Rydal Williams", name));
 
// using the intern method we can get the instance of that string
// or if it doesn't exist it will be added and returned
string dnc = string.Intern("DotNetClr");
Console.WriteLine(Object.ReferenceEquals("DotNetClr", dnc));
 
// is this string really in the pool or not?
Console.WriteLine(string.IsInterned("DotNetClr"));
 
Share this post :

Your Comments.

No comments posted yet.

Your Reply.

Comment Form.

Fields denoted with a "*" are required.

You may also like to leave your email or website.

 
Please add 8 and 5 and type the answer here:

Preview Your Comment.

 
Next entries »