字符串文字会被编译器优化吗? [英] Do string literals get optimised by the compiler?

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

问题描述

C#编译器或.NET CLR是否对字符串文字/常量进行任何巧妙的内存优化?我发誓我听说过字符串内部化"的概念,因此在程序的任何两段代码中,文字"this is a string"实际上是指同一个对象(假设是安全的,字符串是什么)一成不变?).我在Google上找不到任何有用的参考...

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

我听错了吗?不用担心-我不会使用这些信息在代码中做任何可怕的事情,只是想更好地了解它在幕后的工作方式.

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节讨论了 literals 指的是相同的字符串实例,但未提及其他常量字符串表达式.我怀疑这是规范中的疏忽-我将通过电子邮件将其发送给Mads和Eric.

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的答复表明,在Microsoft 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.

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

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