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:
xandzrefers to same object; I can say thatxis interned andzis used taht version. Well, I’m not sure about this; Please correct me, if I am wrong.- I changed the value of
yby 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
.netuses 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?
Yes, constant string expressions in the compiler are treated with
ldstr, which guarantees interning (via MSDN):This isn’t every string; it is constant string expressions in your code. For example:
is only 1 string expression – the IL will be a ldstr on “abcdef” (the compiler can compute the composed expression).
This does not hurt performance.
Strings generated at runtime are not interned automatically, for example:
Here, “abc” is interned, but “abc8” is not. Also note that:
note that
sandtare different references (the literal (assigned tot) is interned, but the new string (assigned tos) is not).