【问题标题】:C# Compile-Time Concatenation For String Constants字符串常量的 C# 编译时连接
【发布时间】:2010-12-18 09:26:18
【问题描述】:

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

【问题讨论】:

    标签: c# string string-concatenation compile-time


    【解决方案1】:

    是的,确实如此。您可以使用 ildasm 或 Reflector 检查代码来验证这一点。

    static void Main(string[] args) {
        string s = "A" + "B";
        Console.WriteLine(s);
    }
    

    被翻译成

    .method private hidebysig static void  Main(string[] args) cil managed {
        .entrypoint
        // Code size       17 (0x11)
        .maxstack  1
        .locals init ([0] string s)
        IL_0000:  nop
        IL_0001:  ldstr      "AB" // note that "A" + "B" is concatenated to "AB"
        IL_0006:  stloc.0
        IL_0007:  ldloc.0
        IL_0008:  call       void [mscorlib]System.Console::WriteLine(string)
        IL_000d:  nop
        IL_000e:  br.s       IL_0010
        IL_0010:  ret
    } // end of method Program::Main
    

    发生了一些更有趣但相关的事情。如果程序集中有字符串文字,CLR 只会为程序集中同一文字的所有实例创建一个对象。

    因此:

    static void Main(string[] args) {
        string s = "A" + "B";
        string t = "A" + "B";
        Console.WriteLine(Object.ReferenceEquals(s, t)); // prints true!
    }
    

    将在控制台上打印“True”!这种优化称为string interning

    【讨论】:

      【解决方案2】:

      根据Reflector

      Console.WriteLine("ABCDEF");
      Console.WriteLine("ABCDEF");
      Console.WriteLine("ABCDEF");
      

      即使在调试配置中。

      【讨论】:

        猜你喜欢
        • 2013-06-25
        • 1970-01-01
        • 2022-01-03
        • 2021-11-18
        • 2020-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多