String Interning

Viewed 675

In the code below, I'm checking the equality of object references.

string x = "Some Text";
string y = "Some Other Text";
string z = "Some Text";

Console.WriteLine(object.ReferenceEquals(x, y)); // False
Console.WriteLine(object.ReferenceEquals(x, z)); // True
Console.WriteLine(object.ReferenceEquals(y, z)); // False

y = "Some Text";

Console.WriteLine(object.ReferenceEquals(x, y)); // True
Console.WriteLine(object.ReferenceEquals(x, z)); // True
Console.WriteLine(object.ReferenceEquals(y, z)); // True

Here:

  • x and z refers to same object; I can say that x is interned and z is used taht version. Well, I'm not sure about this; Please correct me, if I am wrong.
  • I changed the value of y by assigning it the same value as x. I thought it is going to create a new object here; but I was wrong, it used the same reference.

My questions are:

  • Does .net uses string interns for every string that I use?
  • If so, isn't it hurts the performance?
  • If not, how the references became same in above example?
4 Answers
Related