What's the different between ldsfld and ldstr in IL?

前端 未结 3 1439
滥情空心
滥情空心 2021-01-05 03:07

I\'ve read some article about String.Empty vs \"\" and I also do test by my self. Different between them are below.

String.Empty

L_0001: ldsfld strin         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-05 03:36

    The ldsfld operation pushes the value of a static field onto the evaluation stack, while the ldstr pushes a reference to a meta data string literal.

    The performance difference (if any) would be minimal. Newer versions of the compiler actually substitutes "" for String.Empty.

    You should also consider the readability and maintainability of the code. Using String.Empty it's clearer that you actually mean an empty string and not just forgot to type something in the string literal.

    Edit:

    I took a look at the native code created.

    C# 3, release mode, x86:

            string a = String.Empty;
    0000002a  mov         eax,dword ptr ds:[0356102Ch]
    0000002f  mov         dword ptr [ebp-8],eax
            string b = "";
    00000032  mov         eax,dword ptr ds:[0356202Ch]
    00000038  mov         dword ptr [ebp-0Ch],eax
    

    C# 3, release mode, x64:

            string a = String.Empty;
    0000003b  mov         rax,12711050h 
    00000045  mov         rax,qword ptr [rax] 
    00000048  mov         qword ptr [rsp+28h],rax 
            string b = "";
    0000004d  mov         rax,12713048h 
    00000057  mov         rax,qword ptr [rax] 
    0000005a  mov         qword ptr [rsp+30h],rax 
    

    So, in the end the code is identical.

提交回复
热议问题