Increase Startup Time of .Net Application using Ngen.exe

It is an improvement of the .NET JIT compilation.
 
Problem Statement

When we run .net application, code is JIT compiled. Machine code generated by JIT is thrown away after the task compilation. So the same method must be complied again whenever we run the application again.

Compilation of the code again and again is tedious process.
 
Solution : Native Image Generator (Ngen.exe)

  1. It improves the startup time of the application by reducing JIT compilation process at runtime
     
  2. . NGen refers to the process of precompiling (MSIL) executables into the machine code prior to the execution time.
     Which in turn reduces the application startup time by avoiding the need to compile a code at the run time again and again.
     Once an NGen is run against an assembly, the resulting native image is placed into the Native Image Cache and when we run the application it uses the Native cache instead of the recompilation of code.
     
  3. Ngen.exe creates native images, which are files containing compiled processor-specific machine codes, and installs them into the native image cache on the local computer. The runtime can use these native images from the cache instead of using the just-in-time (JIT) compiler to compile the original assembly
     
  4. Ngen also allowed to share same Native image cache with other application so it is helpful in term of memory usage.
     
  5. Native images are typically named such as "*.ni.dll", "*.ni.exe".
     
  6. Steps
     
    • Open VS command prompt
    • Type ngen.exe [option] [assemblyname] [assemblypath]
       
  7. Once you have created the native image for an assembly, the runtime automatically  uses that native image each time it runs the assembly

Running Ngen.exe on an assembly allows the assembly to load and execute faster, because it restores the code and the data structures from the native image cache rather than generating them dynamically.