使用动态类型在.NET中的性能成本性能、成本、类型、动态

2023-09-04 02:04:39 作者:怀念的钟表

什么是使用动态 VS 对象在.NET中的性能成本?例如说我有接受任何类型的参数的方法。例如,

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告诉我,使用动态code时,编译器必须插入一个code块来处理的活力。因此,我想如果用动态到位对象被告知要知道到什么水平这个用法是以牺牲性能为代价?

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反思每一次)。它也可以改变上的操作(例如,取消可空-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)

警告:这是一个测试,可能无法重新您的方案的presentative。这code如下所示

所以:基于一个简单的测试,不是静态的常规C#慢20倍,但比反射快约30倍。

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

更新:有趣的,看起来像反射.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).

 
精彩推荐
图片推荐