Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

cil

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 string [mscorlib]System.String::Empty

""

L_0001: ldstr ""

After I talk with my friends they argue that String.Empty is faster than "" because under the hood (at assembly level) ldstr do more 1 circle than ldsfld. (I can't remember steps that make them different)

I want to know how can I check about this aspect of performance.

like image 526
Anonymous Avatar asked Sep 09 '10 06:09

Anonymous


People also ask

What is Ldstr?

The ldstr instruction pushes an object reference (type O ) to a new string object representing the specific string literal stored in the metadata.

What is better String empty or?

Empty will serve you better than using “”. In the cases where String. Empty will not work either because of the code evaluation OR because of the performance considerations, yes, use “” instead. But, do it because there is a supportable reason, not because you think it may produce faster code.

Does equal String empty?

Using equals Method This technique can be used to check the emptiness of String as well. All you need to do is to call equals() method on empty String literal and pass the object you are testing as shown below : String nullString = null; String empty = new String(); boolean test = "". equals(empty); // true System.


1 Answers

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.

like image 166
Guffa Avatar answered Sep 20 '22 13:09

Guffa