我以前虽然知道这是有可能的,但一直难以相信这一点(接受大家的嘲笑)。直到看了
Jeffrey Richter的Applied Microsoft .NET Framework Programming,不愧是
.net Framework的Bible,说的让人心服口服.
下面是书中所说的一些可能性:
主要原因是在JIT将managed code编译成native code时对于执行环境的了解要
多于unmanaged code.(when the JIT compiler compiles the IL code into
native code at run time, the compiler knows more about the execution
environment than an unmanaged compiler would know.)
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.
原来JIT可以检测到新型CPU并产生适用于这些CPU的专属指令的本地代码。相反,
unmanaged code为了避免兼容的问题,一般会避免新型CPU的专属指令,编译
成面向最小通用集合的本地代码。这样充分利用专属指令的managed code性能
上必然是优的。(我怎么没想到?!)
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.
哈,Richter又提到了这点,JIT可以检测到某些总是返回False的布尔测试,代码量小了,
速度也就快了。
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.
根据执行模式被编译的代码可以重新组织,提高分支预测的成功率!(好厉害的JIT!)
最后Richter说以上只是managed code的性能超过unmanaged code的一部分可能性,
目前managed code的性能已经不错了,还有更大的提升潜力。我对这点坚信不移,.net
程序的性能还是很不错的,以前曾经看到过这方面测试的文章,自己也做过些试验。
最后说一句,Richter的这本书是我看过的最好的.Net书籍,它不会教你怎么去写代码,
用控件,但是它会让你对.Net的内部秘密有所了解,现在我对它已经是爱不释手了:D