2

How smart is the C# compiler, given the following:

float a = 1; //A
var b = 1f; //B
var c = (float)1; //C - Is this line equivalent to A and B?
var d = Convert.ToSingle(1); //D - Is this line equivalent to A and B?

As far as I know, A and B are equivalent after the compilation. What about the other lines?

Are C and D optimized in compile-time to be equivalent to A and B or are they going to be assigned only in run-time, causing more processing to perform the assignment?

I suppose casting (C) must be optimized and the function (D) must not.

In any case, how could I investigate and compare the generated assembly code using VS2012?

j0k
  • 22,600
  • 28
  • 79
  • 90
natenho
  • 5,231
  • 4
  • 27
  • 52
  • I am pretty sure `var` is calculated at compile time (the type is at least). As opposed to `dynamic` – musefan May 16 '13 at 16:30
  • 1) The code, as is, won't compile, as you're redefining `x`. Give each line a different variable name. 2) After fixing #1 the program will be compilable. Rather than asking us about a, b, c, and d, why not compile the program yourself and find out? It'll be quicker and easier than asking the question here. – Servy May 16 '13 at 16:32
  • @Jon Yeah, already edited ;) – Servy May 16 '13 at 16:33
  • Sorry, I didn't mention the lines are not part of a program. I'm just making a comparison between the approaches. – natenho May 16 '13 at 17:38

2 Answers2

4

The three first lines are equivalent; in fact they compile down to the same IL (at least with the .NET 4 compiler that I used).

The fourth is a runtime conversion performed by calling a method, which is a completely different beast.

Regarding the inspection of generated IL, take a look at A tool for easy IL code inspection.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Great answer, I use LINQPad, but I've never noticed this feature, it's really easy to use. Thank you! – natenho May 16 '13 at 17:45
1

how could I investigate and compare the generated assembly code using VS2012?

"Go To Assembly" ( or press CTRL+ALT+D )

Answers are below ....

            float x = 1; //A
00000061  fld1 
00000063  fstp        dword ptr [ebp-40h] 
            var x1 = 1f; //B
00000066  fld1 
00000068  fstp        dword ptr [ebp-44h] 
            var x2 = (float)1; //C - Is this line equivalent to A and B?
0000006b  fld1 
0000006d  fstp        dword ptr [ebp-48h] 
            var x3= Convert.ToSingle(1); //D - Is this line equivalent to A and B?
00000070  mov         ecx,1 
00000075  call        5FB7A2DC 
0000007a  fstp        dword ptr [ebp-50h] 
0000007d  fld         dword ptr [ebp-50h] 
00000080  fstp        dword ptr [ebp-4Ch] 
Damith
  • 62,401
  • 13
  • 102
  • 153