At first view, you can think that dynamic types come with C# 4.0 are only used for to make a type written outside the .Net environment applicable in .Net environment. However, we can achieve important performance earnings when we use Dynamic types instead of Reflection types while coding by using Reflection types. Therefore, it makes sense to use Dynamic types instead of Reflection types in the applications developed by using C# 4.0.
In the example below, we have two classes named Music and Video that apply IMedia interface. In this simple console application I prepared, I created Music and Video objects and I called generic PlayMedia<T> method that performs Play operations of these objects. Depending on the scenario, in order to make the use of reflection or dynamic type necessary, I designed this application that any object that includes Play method can be used in PlayMedia method. The Play method of media object which’s type is uncertain during the compiling is called by using dynamic type in the lines numbered 20 and 21 of PlayMedia method. If you want to test the usage of Reflection types, you can turn the lines 20 and 21 to comment lines and remove the comment tags in the line numbered 19. First, I see the results by operating only the line 19. Then, when I operate the lines 20 and 21, the difference between the results is highly impressive :)
Reflection is trying to reach the members included in a type such as method and field by analyzing the structure of the type. However, using dynamic type can reach the result faster because dynamic type achieves the intended member directly without analyzing the type. Anyway, you can see the speed difference if you test this issue as given below.
The class diagram of the types used in the example is given below.
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 Music m = new Music { FileName = "amazing.mp3" };
6 Video v = new Video { FileName = "avatar_fragman.wmv" };
7
8 PlayMedia<Music>(m);
9 PlayMedia<Video>(v);
10 Console.ReadLine();
11 }
12
13 static void PlayMedia<T>(T media)
14 {
15 DateTime d1, d2;
16 d1 = DateTime.Now;
17 for (int i = 0; i < 1000000; i++)
18 {
19 //media.GetType().GetMethod("Play").Invoke(media, null);
20 dynamic d = media;
21 d.Play();
22 }
23
24 d2 = DateTime.Now;
25 TimeSpan t = d2 - d1;
26
27 Console.WriteLine(t.TotalSeconds);
28 }
29 }
As can be seen from the test results, the process done upon 1.000.000 record by using reflection type takes 1.85 seconds whereas when I use dynamic type, it takes average 0.17 seconds. Therefore, we can achieve the result 10 times faster when we use dynamic type. Of course, different results can be obtained in different scenarios but we can say that dynamic type is clearly faster than reflection types. It is obvious that, dynamic type is a better choice in terms of performance in these types of processes.