字符串实习 [英] String Interning

查看:46
本文介绍了字符串实习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我正在检查对象引用的相等性.

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

这里:

  • x z 指的是同一对象;我可以说 x 是被拘禁的,而 z 是taht版本的.好吧,我对此不确定.如果我错了,请纠正我.
  • 我通过给 y 赋了与x相同的值来更改它的值.我以为它将在这里创建一个新对象;但是我错了,它使用了相同的参考.
  • 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.

我的问题是:

  • .net 是否使用字符串实习生为我使用的每个字符串?
  • 如果是这样,这是否会损害性能?
  • 如果不是,那么上例中的引用如何相同?
  • 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?

推荐答案

是的,编译器中的常量字符串表达式使用 ldstr 进行处理,这保证了实习(通过

Yes, constant string expressions in the compiler are treated with ldstr, which guarantees interning (via MSDN):

公共语言基础结构(CLI)确保引用两个具有相同字符序列的元数据令牌的两个ldstr指令的结果恰好返回相同的字符串对象(此过程称为字符串插入").

The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning").

这不是每个字符串;它是代码中的常量字符串表达式.例如:

This isn't every string; it is constant string expressions in your code. For example:

string s = "abc" + "def";

只有1个字符串表达式-IL将是"abcdef"上的ldstr(编译器可以计算组成的表达式).

is only 1 string expression - the IL will be a ldstr on "abcdef" (the compiler can compute the composed expression).

这不会影响性能.

在运行时 生成的字符串不会自动被检查,例如:

Strings generated at runtime are not interned automatically, for example:

int i = GetValue();
string s = "abc" + i;

在这里,"abc"被屏蔽,但"abc8"不是.另请注意:

Here, "abc" is interned, but "abc8" is not. Also note that:

char[] chars = {'a','b','c'};
string s = new string(chars);
string t = "abc";

请注意, s t 是不同的引用(文字(分配给 t )被插入,但是新的字符串(分配给 s )不是).

note that s and t are different references (the literal (assigned to t) is interned, but the new string (assigned to s) is not).

这篇关于字符串实习的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆