Is there any performance increase by changing this .NET string to a const? Does the IL automatically do that?

前端 未结 4 1152
深忆病人
深忆病人 2021-01-24 13:07

Given the following simple .NET code, is there any difference between these two, under the hood with respect to the string \"xml\"?

if (extension.Eq         


        
4条回答
  •  一个人的身影
    2021-01-24 13:56

    It is the same for the compiler. Basically both variables have no way of being changed at runtime.

    This is an example:

    public static void Main()
    {
        Console.WriteLine("Hello World");
    
        const string hello = "Hello World";
        Console.WriteLine(hello);
    }
    

    Compiles to:

    .method public hidebysig static void  Main() cil managed
      {
        // 
        .maxstack  8
        IL_0000:  nop
        IL_0001:  ldstr      "Hello World"
        IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
        IL_000b:  nop
        IL_000c:  ldstr      "Hello World"
        IL_0011:  call       void [mscorlib]System.Console::WriteLine(string)
        IL_0016:  nop
        IL_0017:  ret
      }
    

    As you can see they are exactly the same. Compiler uses ldstr to push a string object for the literal string.

    You can move const string outside method and it won't make a difference, because literals are treated as consts.

提交回复
热议问题