托管程序优于非托管程序的地方

传统的C/C++编译生成的应用一般属于非托管应用程序,而基于.NET框架,通过CLR、JIT来编译生成的应用程序属于托管应用程序。

一般的理解,非托管程序肯定要优于托管程序的,为什么呢?因为非托管程序省略了CLR加载、JIT编译的过程,而直接编译成本地CPU执行的指令的。

那么托管程序较非托管程序,到底好在哪里呢?

最主要一点就是JIT编译器在将IL代码编译成本地CPU指令时,会获取更多的执行环境信息,这样它就能针对特定的CPU指令进行特定优化。

下面列出了托管程序较非托管程序的几个优点:

1.  A JIT compiler could detect that the application is running on a Pentium 4 and produce native code that takes advantage of any special instructions offered by the Pentium 4. Usually, unmanaged applications are compiled for the lowest−common−denominator CPU and avoid using special instructions that would give the application a performance boost over newer CPUs.

2. A JIT compiler could detect that a certain test is always false on the machine that it is running on. For example, consider a method with code like this:
if (numberOfCPUs > 1) {
Ã
}
This code could cause the JIT compiler not to generate any CPU instructions if the host machine has only one CPU. In this case, the native code has been fine−tuned for the host machine: the code is smaller and executes faster.
·
3. The CLR could profile the code’s execution and recompile the IL into native code while the application runs. The recompiled code could be reorganized to reduce incorrect branch predictions depending on the observed execution patterns.


PS:

如果觉得您生成的托管程序确实比非托管程序性能低下,那么MS也提供了一个工具--NGen.exe,用来将IL代码编译成本地代码并保存到文件,下次再运行的时候,CLR会直接加载该文件运行,省却了JIT的中间编译过程,这会提升不少的性能。

NGen.exe使用说明见: http://msdn.microsoft.com/zh-cn/library/6t9t5wcf.aspx

你可能感兴趣的:(托管程序优于非托管程序的地方)