C# 字符串常量的编译时串联
C# 是否对常量字符串连接进行编译时优化?如果是这样,我的代码必须如何编写才能利用这一点?
示例:这些在运行时如何比较?
Console.WriteLine("ABC" + "DEF");
const string s1 = "ABC";
Console.WriteLine(s1 + "DEF");
const string s1 = "ABC";
const string s2 = s1 + "DEF";
Console.WriteLine(s2);
Does C# do any compile-time optimization for constant string concatenation? If so, how must my code by written to take advantage of this?
Example: How do these compare at run time?
Console.WriteLine("ABC" + "DEF");
const string s1 = "ABC";
Console.WriteLine(s1 + "DEF");
const string s1 = "ABC";
const string s2 = s1 + "DEF";
Console.WriteLine(s2);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,确实如此。您可以使用 ildasm 或 Reflector 检查代码来验证这一点。
翻译为
有一些更有趣但相关的事情发生了。如果程序集中有一个字符串文字,则 CLR 将仅为程序集中该同一文字的所有实例创建一个对象。
因此:
将在控制台上打印“True”!这种优化称为字符串驻留。
Yes, it does. You can verify this using by using
ildasm
or Reflector to inspect the code.is translated to
There is something even more interesting but related that happens. If you have a string literal in an assembly, the CLR will only create one object for all instances of that same literal in the assembly.
Thus:
will print "True" on the console! This optimization is called string interning.
根据 Reflector:
即使在调试配置中也是如此。
According to Reflector:
even in a Debug configuration.