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

前端 未结 4 1179
深忆病人
深忆病人 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:35

    There is no difference due to the fact that literal strings are normally interned by the compiler.

    All the following examples will print out true:

    • Example 1:

      const string constHello = "Hello";
      
      void Foo()
      {
          var localHello = "Hello";
          Console.WriteLine(ReferenceEquals(constHello, localHello));
      }
      
    • Example 2:

      string fieldHello = "Hello";        
      
      void Foo()
      {
          var localHello= "Hello";
          Console.WriteLine(ReferenceEquals(fieldHello, localHello));
      }
      
    • Example 3:

      const string constHello = "Hello";
      
      void Foo()
      {
          Console.WriteLine({IsReferenceEquals("Hello")}");
      }
      
      public static bool IsReferenceEquals(string s) => ReferenceEquals(constHello, s);
      

    In all cases, there is only one instance of "Hello".

提交回复
热议问题