Monday, September 14, 2009

Catching inlining in the act from managed code.

This blog post shows ilining in action all without leaving the comfort of managed code.

When you compile C# code it is compiled to Intermediate Language (IL).  When the Common Language Runtime executes IL it uses a Just In Time (JIT) compiler to compile the IL to machine instructions.
Here is some C# sample code:

using System;
using System.Diagnostics;
static class Program
    static void Main() { Person me = new Person("Dave"); Console.ReadKey(); }
class Person
    public Person(string name) { Name = name; }
    private void SetName(string name)
        Console.WriteLine(new StackTrace().GetFrame(1).GetMethod().Name);
    public string Name
        set { SetName(value); }

Copy that code into notepad and save it as Program.cs.
From a Visual Studio command prompt type these lines.
csc /out:d.exe Program.cs /optimize- /debug+ 
csc /out:u.exe Program.cs /optimize- /debug- 
csc /out:o.exe Program.cs /optimize+ /debug- 

Then execute the programs:
d outputs set_None
u outputs .ctor
o outputs Main

Kinda crazy huh?

PS. if you run this program from Visual Studio it will output set_None because you run with a debugger attached and the JIT Compiler won't inline.  If you compile in Release mode and run without the debugger (ctrl+F5) you can see Main if you are fast enough ;)

No comments: