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)
{
}
or
public void Foo(dynamic obj)
{
}
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?
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: these are for a single test that may not be representative of your scenario. This code is shown here
So: based on a simple test, about 20-times slower than static regular C#, but about 30 times faster than reflection.
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
Here it is only about 12 times faster than reflection, because reflection got faster (not because dynamic got slower).