在.NET中使用动态类型的性能成本 [英] Performance cost of using dynamic typing in .NET

查看:201
本文介绍了在.NET中使用动态类型的性能成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中使用动态对象的性能成本是多少?说例如我有一个方法接受任何类型的参数。 EG

What is the performance cost of using dynamic vs object in .NET? Say for example I have a method which accepts a parameter of any type. E.G.

public void Foo(object obj)
{
}

public void Foo(dynamic obj)
{
}



ILSpy告诉我使用动态代码,编译器必须插入一个代码块来处理动态。因此,我想知道如果使用动态代替对象是建议和这个用法是以性能为代价的什么级别?

ILSpy tells me that when using dynamic code, the compiler must insert a code block to handle dynamism. Therefore I want to know if using dynamic in place of object is advised and to what level this usage comes at the cost of performance?

推荐答案

这将取决于确切的情况 - 但是有一个内置的缓存层,所以它不是可怕的,你可能期望(它不会做反射每次)。它也可以根据操作变化(例如,提升可空T操作明显更慢)。你需要测量,但是因为它发生我有一些时间在这里成员(属性)访问,我在做 FastMember

That would depend a lot on the exact scenario - but there is a layer of caching built in, so it is not as terrible as you might expect (it doesn't do reflection every time). It can also vary on the operations (for example, "lifted" nullable-T operations are noticeably slower). You would need to measure, but as it happens I have some timings here for member (property) access, that I took when doing FastMember:

Static C#: 14ms
Dynamic C#: 268ms
PropertyInfo: 8879ms (aka reflection)
PropertyDescriptor: 12847ms (aka data-binding)
TypeAccessor.Create: 73ms (aka FastMember)
ObjectAccessor.Create: 92ms (aka FastMember)



CAVEAT:这些是针对单次测试,场景。此代码是此处显示

因此:基于简单测试,比静态常规C#慢20倍,但是比反射快30倍。

So: based on a simple test, about 20-times slower than static regular C#, but about 30 times faster than reflection.

UPDATE:有趣,看起来反射在.NET 4.5中更快:

UPDATE: interesting, looks like reflection got faster in .NET 4.5:

Static C#: 13ms
Dynamic C#: 249ms
PropertyInfo: 2991ms
PropertyDescriptor: 6761ms
TypeAccessor.Create: 77ms
ObjectAccessor.Create: 94ms

这里只比反射快12倍,因为反射更快(不是因为动态变慢了)。

Here it is only about 12 times faster than reflection, because reflection got faster (not because dynamic got slower).

这篇关于在.NET中使用动态类型的性能成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆