Friday, June 4, 2010

How JIT or runtime compilation happens

Ever wondered how .net runtime compilation works? Let me try to explain it to the best of my understanding.
Lets take an example


namespace TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteHello();
        }

        public static void WriteHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

At the runtime when CLR would see that there is a call to a function WriteHello, it will try to find out all the types used inside the function (here there is only one "Console"). It will then create an internal datastructure and put all the available members of those types into there and point them to an internal function "JITCompiler" something like as following




Then CLR invokes JITCompiler for all functions which have been used inside the current method for e.g. here we have only one function WriteLine. JITCompiler goes to assembly for type Console and looks into its metadata table. From there it will find the information about the actual implementation (IL code) of the function WriteLine. It creates some memory block and compiles that IL code to native memory using those blocks. it comes back and changes the pointer (which was earlier pointing to itself) to that memory block. refer following picture















* please note that the function compiled should be void writeline(string s) (not void writeline). I shall correct the image sometime later.

After JITCompiler job is done, it returns cursor back to Main function. Now CLR goes in Main function once again and executes it. Not to mention, that next time whenever JITCompiler will be invoked, it will work only for those functions who are pointing to it that means runtime compilation will happen only once. Kindly note that all native memory will be in persistance until your application is up, whenever you make any changes to your .vb or .cs file, it causes your application to be shutdown forcefully and start a new instance. As soon as your application will go down, all compiled code (into native memory) will be flushed and the whole process (runtime compilation) will start again for new instance of application.
Since all the runtime compilation logic is inside function JITCompiler, people don't mind calling the complete process itself is JIT compilation.

Hope this will clear your at least one important low level aspect of ASP.NET.

No comments:

Post a Comment