Tuesday, May 17, 2011

performance - C# Dynamic Keyword — Run-time penalty?

I have done some ad-hock performance comparison testing
between JavaScript and C# (more about this some other time),
and between C# value type (int), object and dynamic, and results are "interesting".
"object" is 2.5 x slower than "int", and "dynamic" is 10x slower than "object".
Same exact combinatorial code... Beware of "dynamic" tax!

Here is an explanation from StackOverflow, by
Eric Lippert, a principal developer on the Microsoft Visual C# compiler team.

performance - C# Dynamic Keyword — Run-time penalty? - Stack Overflow

However, let's consider the performance implications of some operations at an abstract level. Suppose you have:

int x = 123;
int y = 456;
int z = x + y;

Adding two integers takes about a billionth of a second on most hardware these days.

What happens if we make it dynamic?

dynamic x = 123;
dynamic y = 456;
dynamic z = x + y;

Now what does this do at runtime? This boxes 123 and 456 into objects, which allocates memory on the heap and does some copies.

Then it starts up the DLR and asks the DLR 'has this code site been compiled once already with the types for x and y being int and int?'

The answer in this case is no. The DLR then starts up a special version of the C# compiler which analyzes the addition expression, performs overload resolution, and spits out an expression tree describing the lambda which adds together two ints. The DLR then compiles that lambda into dynamically generated IL, which the jit compiler then jits. The DLR then caches that compiled state so that the second time you ask, the compiler doesn't have to do all that work over again.

That takes longer than a nanosecond. It takes potentially many thousands of nanoseconds.