In C#, should I use string.Empty or String.Empty or “” to intitialize a string?

前端 未结 30 2503
挽巷
挽巷 2020-11-22 02:06

In C#, I want to initialize a string value with an empty string.

How should I do this? What is the right way, and why?

string willi = string.Empty;
         


        
30条回答
  •  -上瘾入骨i
    2020-11-22 02:40

    There really is no difference from a performance and code generated standpoint. In performance testing, they went back and forth between which one was faster vs the other, and only by milliseconds.

    In looking at the behind the scenes code, you really don't see any difference either. The only difference is in the IL, which string.Empty use the opcode ldsfld and "" uses the opcode ldstr, but that is only because string.Empty is static, and both instructions do the same thing. If you look at the assembly that is produced, it is exactly the same.

    C# Code

    private void Test1()
    {
        string test1 = string.Empty;    
        string test11 = test1;
    }
    
    private void Test2()
    {
        string test2 = "";    
        string test22 = test2;
    }
    

    IL Code

    .method private hidebysig instance void 
              Test1() cil managed
    {
      // Code size       10 (0xa)
      .maxstack  1
      .locals init ([0] string test1,
                    [1] string test11)
      IL_0000:  nop
      IL_0001:  ldsfld     string [mscorlib]System.String::Empty
      IL_0006:  stloc.0
      IL_0007:  ldloc.0
      IL_0008:  stloc.1
      IL_0009:  ret
    } // end of method Form1::Test1
    
    .method private hidebysig instance void 
            Test2() cil managed
    {
      // Code size       10 (0xa)
      .maxstack  1
      .locals init ([0] string test2,
                    [1] string test22)
      IL_0000:  nop
      IL_0001:  ldstr      ""
      IL_0006:  stloc.0
      IL_0007:  ldloc.0
      IL_0008:  stloc.1
      IL_0009:  ret
    } // end of method Form1::Test2
    

    Assembly code

            string test1 = string.Empty;
    0000003a  mov         eax,dword ptr ds:[022A102Ch] 
    0000003f  mov         dword ptr [ebp-40h],eax 
    
            string test11 = test1;
    00000042  mov         eax,dword ptr [ebp-40h] 
    00000045  mov         dword ptr [ebp-44h],eax 
    
            string test2 = "";
    0000003a  mov         eax,dword ptr ds:[022A202Ch] 
    00000040  mov         dword ptr [ebp-40h],eax 
    
            string test22 = test2;
    00000043  mov         eax,dword ptr [ebp-40h] 
    00000046  mov         dword ptr [ebp-44h],eax 
    

提交回复
热议问题