使用“动态”与“对象”的性能成本? [英] Performance cost of using `dynamic` vs `object`?

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

问题描述

在.NET中使用 dynamic object 相比,性能成本是多少?

What is the performance cost of using dynamic vs object in .NET?

例如,我有一个接受任何类型参数的方法。 EG

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:这些是针对单个测试的,可能不代表您场景。这段代码是此处显示

CAVEAT: these are for a single test that may not be representative of your scenario. This code is shown here

所以:基于一个简单的测试,它比静态常规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).

这篇关于使用“动态”与“对象”的性能成本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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