Tuesday, April 22, 2008

Compiling .NET to Machine Code

Compiling .NET to Machine Code
Normally, when a .NET application is run, the JIT (Just In Time) compiler transforms the .NET intermediate code into machine code just before it gets executed. Because of this, the compiler only has very little time to optimize the code.
However, there's a feature many .NET developers aren't even aware of: ahead-of-time compilation or AOT in short. AOT means compiling an entire .NET assembly to machine code before it is executed and usually takes place either when the an application is installed or continuously in the background while the system is idle. It allows for time-consuming optimizations to be performed on the code that normally only a traditional C or C++ compiler would have time to do.
The advantage of this method over traditional compilation however is that it takes place on the end-user's machine. Microsoft's .NET framework for example will compile .NET 2.0 assemblies to 32 bit code on a 32 bits operating system and to 64 bit code on a 64 bits operating system unless you tell it to do otherwise.
Microsoft .NET Framework
Microsoft's utility for AOT compilation is named ngen.exe, short for native image generator. It can be found in the directory the .NET runtime is installed in, eg. C:\Windows\Microsoft.NET\Framework\v2.0.50727 for the .NET Framework 2.0.
ngen.exe can be invoked from the command line in two different modes:
ImmediateUse ngen install or ngen update to immediately compile the given assembly to machine code. ngen.exe will compile the assembly and exit when it's done.
QueuedUsing this mode, assemblies are placed into a queue and will be compiled either at your measure or by a low-priority process while the system is idle. This mode can be accesses by adding the /queue:{123} argument at the command line.
ngen.exe will not modify the assemblies specified on the command line but instead put the compiled assemblies into a special folder that is checked whenever .NET needs to load an assembly.
(taken from

1 comment:

Fondea said...

Well said.