Does it make sense to NGen – compile your ASP.NET MVC application ?

By Mirek on (tags: NGen CIL JIT-compilation, categories: architecture, tools)

In .Net world every line of code has to be compiled before it can be executed obviously. However the compilation process occurs twice. First the Common Intermediate Language (CIL) is produced out of human readable code and it occurs just after the development process. Then the CIL is compiled into the native code specifically to be interpreted  by the target machine. The letter step occurs on the fly, on client machine and is called the JIT (Just In Time) compilation.

The JIT-compilation is the process of translating the universal CIL to the machine specific code so the application is executed in best possible way. The JIT-compilation occurs on the method level on the fly, so when specific method is called then it is compiled and cached for the first time, then executed. The process is well explained here or here.

Since the Just In time compilation has a lot of advantages some of the sources suggests that it might sometime be better to have the CIL already precompiled ahead. One of the benefits might be the performance gain on the application startup. To precompile the application CIL and create the native machine code image we have to use the Native Image Generator (NGen.exe). This is a tool that compiles the CIL the to machine code in advance and does it on a assembly level. This is widely explained here.
Basically if we have our application already compiled in current machine code then we should expect the cold start up of the application should be faster.
To check that I’ve recently did some tests with some of our ASP.NET MVC web applications. The problem was it has quite a long cold startup time. So, without getting into a technical details, I first started the application few times with a normal flow, so to speak, letting the JIT compilation happen by default. Secondly I did the NGEN generation before each application cold start. By the cold start I mean the application was just deployed and added to IIS.
The results were somehow predictable as I’ve read here, here, here or here. The NGEN’ed application cold start performance gain was either unnoticeable, reaching something about up to few percent or sometimes even worse than normal JIT. 
Maybe in some edge cases the performance gain would be considerably bigger, but not in my tests. Anyway taking all of the cons of using precompiled native images instead of real time compilation makes it all not worth the efforts.

The good thing is however I could did some review of my knowledge of how the whole CLR works behind the scenes. Thus I recommend to read all linked articles included in this post, since they fully explain the pre compilation topic as well as the overall application performance considerations.