Monday, June 8, 2015

CLR Compiler optimizations visible in IL

Once again, I was trying to see the effects of the structure of the C# and compilation process, on the IL. The compiler performs numerous optimizations if we run it with the -o+ flag. One of which is method inlining, but it's a lot smarter than that. It can also pre-calculate certain values while compiling to IL.

So let's take that sample application again I'm using:

As you can see - I decorated the Add() method with the MethodImpl attribute - set to AggressiveInling. This should trigger the compiler to 'inline' the method: paste the instructions into the control flow of the Main() method.

After compilation, let's check out ildasm:

As you can see, the IL looks the same as it did before. Compiling it with -o+ maybe?

Nope, the method instructions aren't inlined. So, at first I thought that I was doing something wrong. As it turns out, you will not see the inlining happening in ildasm.

Note that all the 'nop' operators are gone in this version of the IL, since I used the -o+ flag.

But how about that inlining then? Well - I ran the application and used !dumpil in windbg. As you can see now ( bottom left ) the IL code for adding the two numbers, is inlined in the Main() method:

That's cool! But the optimizers can do a whole lot more ( so I've heard ). The can also pre-calculate values that will be constant at runtime. So in order to demonstrate that, I slightly re-wrote the application and add the two number in the Main() method. Now - check out the yellow IL code. There is no line with 'add' in the IL ! The value 4 was calculated by the CLR compiler and just written to the console:

Cool huh?!

If you want to know why I'm diving into these topics and where I learnt how to do it? Read this. I'm just doing what I saw Bart de Smet do on PluralSight

No comments:

Post a Comment