Introduction
I would like to share the basics of Ngen.exe in .Net. I will first try to explain the problem then the solution, Ngen.exe.
I collected this material from various web resources and I am trying to explain it in simple words.
Problem Statement
When we run a .Net application, the 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 a tedious process.
Solution
Native Image Generator (Ngen.exe)
- It improves the startup time of the application by reducing JIT compilation process at runtime.
- 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 the code at ru 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.
- Ngen.exe creates native images, that 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.
- Ngen also allows sharing the same Native image cache with another application so it is helpful in terms of memory usage.
- Native images are typically named such as "*.ni.dll", "*.ni.exe".
- Procedure:
- Open Visual Studio command prompt
- Type: ngen.exe [option] [assemblyname] [assemblypath]
- 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.
References
Ngen.exe (Native Image Generator)
Conclusion
We can improve the startup time of .Net applications using Native image generator.