C#做字符串得到由编译器优化? [英] C# do string literals get optimised by the compiler?

查看:198
本文介绍了C#做字符串得到由编译器优化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问C#编译器或.NET CLR做字符串/常量的任何聪明的内存优化?我可以发誓,我听说字符串内部化,以便在程序code中的任何两位,文字这是一个字符串实际上指的是同一对象的概念的(presumably安全,用绳子是不可变的?)什么。我找不到任何有用的参考,以它在谷歌虽然...

Does the C# compiler or .NET CLR do any clever memory optimisation of string literals/constants? I could swear I'd heard of the concept of "string internalisation" so that in any two bits of code in a program, the literal "this is a string" would actually refer to the same object (presumably safe, what with strings being immutable?). I can't find any useful reference to it on Google though...

,我都听见了?别担心 - 我没有做任何事情太可怕了,我code。与此信息,只是想更好地我它是如何工作的幕后理解

Have I heard this wrong? Don't worry - I'm not doing anything horrible in my code with this information, just want to better my understanding of how it works under the covers.

推荐答案

编辑:虽然我强烈怀疑下面的语句是为所有的C#编译器实现真实的,我不知道它在规范实际上保证。有关的文字规范会谈第2.4.4.5 的引用相同的字符串实例,但它并没有提及其他字符串常量前pressions。我的犯罪嫌疑人的这是在规范监督 - 我会通过电子邮件的Mads和埃里克它

While I strongly suspect the statement below is true for all C# compiler implementations, I'm not sure it's actually guaranteed in the spec. Section 2.4.4.5 of the spec talks about literals referring to the same string instance, but it doesn't mention other constant string expressions. I suspect this is an oversight in the spec - I'll email Mads and Eric about it.

这不只是字符串。这是任何字符串的的。因此,例如,考虑:

It's not just string literals. It's any string constant. So for example, consider:

public const string X = "X";
public const string Y = "Y";
public const string XY = "XY";

void Foo()
{
    string z = X + Y;
}

编译器实现,这里的级联(用于以Z )是两个常量字符串之间,所以结果也是一个常量字符串。因此,以Z 的初始值是一样的引用作为 XY 的价值,因为他们是在编译时具有相同值的常量。

The compiler realises that the concatenation here (for z) is between two constant strings, and so the result is also a constant string. Therefore the initial value of z will be the same reference as the value of XY, because they're compile-time constants with the same value.

编辑:从的Mads和Eric答复建议,在微软C#编译器字符串常量和字符串文字的的通常的处理方式相同 - 但其他实现可能会有所不同。

The reply from Mads and Eric suggested that in the Microsoft C# compiler string constants and string literals are usually treated the same way - but that other implementations may differ.

这篇关于C#做字符串得到由编译器优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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