字符串实习

编程入门 行业动态 更新时间:2024-10-26 15:13:41
本文介绍了字符串实习的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

我的问题是:

  • 是否使用字符串实习生为我使用的每个字符串?
  • 如果是这样,这是否会损害性能?
  • 如果不是,那么上例中的引用如何相同?
  • Does 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 进行处理,这保证了实习(通过 MSDN ):

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).

更多推荐

字符串实习

本文发布于:2023-11-13 09:23:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583997.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!