Occasionally Relevant Insights from a Software Builder


Making .NET Faster with NGen

The one thing that concerns me about compiling a .NET application is that it doesn’t produce machine code (i.e. code that runs directly on a machine’s CPU). Instead, it creates code in the Microsoft Intermediary Language (MSIL). When you run the program, it use the just-in-time (JIT) compiler to produce native code.

When you run a .NET application, there is a slight delay before it starts. This is the JIT compiling it to machine code. Unfortunately, the native code isn’t stored permanently. It only stays in the running process’ memory space and disappears when the process stops running.

This is where an application in the .NET Framework that few people know about can be used. The Microsoft Native Image Generator (NGen) precompiles MSIL executables to platform specific native code before they are run. The application is then stored in the native image cache. The next time you run the program, it will run it from the cache and you won’t experience the .NET delay when an application starts.

NGen typically (but not always) improves the warm startup time of applications and occasionally the cold startup time. Warm startup time refers to the time it takes to start an application that was run recently (not between reboots). Cold startup time is the time it takes to run an application for the first time time since the computer was booted.

NGen.exe can be found in the .NET Framework folder in Windows, i.e. C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727. There is also a version of it in .NET 1.0. While there are many options for this application, you can run it by specifying a .NET program as a parameter, i.e.

ngen Test.exe

This will compile the MSIL Test.exe program to native code which then gets stored in the native image cache. The next time you run this program, it will be run from cache instead of getting compiled by JIT.

I should note that using NGen for .NET server applications won’t make much of a difference. There will only be a delay in start time the first time the application is run. Afterwards, it will run faster because it is already in memory. NGen works best with .NET client applications.

Leave a Reply

Your email address will not be published. Required fields are marked *