.NET 4.0 下 typeof() 的性能问题

    技术2026-04-20  5

     

    前段时间为一个基于.NET 2.0开发的ESB项目作性能调优,在验证其是否能够无痛升级到.NET 4.0框架时发现typeof()运算符在两个版本框架下有完全不同的性能表现,特记录在此,也算是一个Tips.

     

    测试代码如下:

    class Program { static void Main(string[] args) { int loopCount = 100000000; Bar bar = new Bar(); CodeTimer.Time("Bar.GetType()", loopCount, new CodeTimer.ActionDelegate(bar.SomeMethod)); Foo foo = new Foo(); CodeTimer.Time("typeof(Foo)", loopCount, new CodeTimer.ActionDelegate(foo.SomeMethod)); Console.ReadLine(); } } public class Bar { public void SomeMethod() { Logger.Log(this.GetType(), "SomeMethod started..."); } } public class Foo { //private static readonly Type myType = typeof(Foo); public void SomeMethod() { Logger.Log(typeof(Foo), "SomeMethod started..."); } } public class Logger { public static void Log(Type type, string text) { } } 

     

    在项目的目标框架为.NET 2.0时输出如下:

     

    在项目的目标框架为.NET 4.0时输出如下:

     

    可以看到GetType在.NET 4下的表现虽然也有所下降,但还不至于像typeof这么夸张。

    使用Reflector查看IL,发现不管是.NET 2.0还是4.0,调用typeof都是这一句:

    call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)  

    如果去掉程序代码中的注释,在Foo.SomeMethod中使用myType,则.NET 4.0下的耗时可以加速到1715ms,这么看来4.0下GetTypeFromHandle的native code实现不再缓存对象类型。如果原先跑2.0的项目里没有显示的缓存类型,升级时最好还是改一下。

     

    btw, 看到网上有种说法:If you're running on a 64 bit machine, make sure the build is set to "Any CPU" rather than "x86".否则在4.0上的运行速度较2.0有显著差距,不过我还没验证过。

     

    最新回复(0)