Thursday, March 3, 2011

dynamic vs reflection performance comparison

  • Visual C# 2010 introduces a new keyword, dynamic which is a static type, but an object of type dynamic bypasses static type checking. So C# can use the features of dynamic language.
  • The same feature can be used to invoke methods dynamically from .net assemblies.
  • Until C# 3.0 in order to invoke methods dynamically from .net assemblies we were using reflection.
  • From C# 4.0 we can achieve this using dynamic keyword elegantly.
  • For example if we want to call a method named Test from Class Class1 dynamically using dynamic keyword.
 Assembly ass = Assembly.Load("MyAssembly2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
 dynamic obj = ass.CreateInstance("MyAssembly2.Class1");
 obj.Test();
This code would compile in C# 4.0 as the Test() method will be resolved in runtime.
I tried to compare the performance impact of using dynamic keyword by invoking the method 900000 times in a loop Following is the responses for different scenarios.
  • Static : 10 milliseconds
  • Through Reflection : 1635 milliseconds
  • Through dynamic : 115 milliseconds
Dynamic Method invocation is around 15 Times faster than Reflection code.
It looks better to use dynamic in places where reflection is used as it is more performing and elegant.

No comments:

Post a Comment