MS C# compiler and non-optimized code

Viewed 1042

Note: I noticed some errors in my posted example - editing to fix it

The official C# compiler does some interesting things if you don't enable optimization.

For example, a simple if statement:

int x;
// ... //
if (x == 10)
   // do something

becomes something like the following if optimized:

ldloc.0
ldc.i4.s 10
ceq
bne.un.s do_not_do_something
// do something
do_not_do_something:

but if we disable optimization, it becomes something like this:

ldloc.0
ldc.i4.s 10
ceq
ldc.i4.0
ceq
stloc.1
ldloc.1
brtrue.s do_not_do_something
// do something
do_not_do_something:

I can't quite get my head around this. Why all that extra code, which is seemingly not present in the source? In C#, this would be the equivalent of:

int x, y;
// ... //
y = x == 10;
if (y != 0)
   // do something

Does anyone know why it does this?

3 Answers
Related