I reproduced: http://www.cnblogs.com/cuitsl/archive/2012/01/06/2314636.html
COMPARISON WITH REFLECTION
First, we can see that dynamic requires less code than reflection to perform the same operation.
For example, call the GetName () method in the Me class.
Class Me
{
Public string Blog {get; set ;}
Public string GetName ()
{
Return "Zhenxing Zhou ";
}
}
Call the GetName () method using reflection:
Assembly a = Assembly. GetExecutingAssembly ();
Object instance = a. CreateInstance ("Xianfen. Net. TestDynamic. Me ");
Type type = instance. GetType ();
MethodInfo mi = type. GetMethod ("GetName ");
Object result = mi. Invoke (instance, null );
The same dynamic call:
Dynamic myInfo = new Me ();
String result = myInfo. GetName ();
The following is an example of reflection without using dynamic.
Class Program
{
Static void Main (string [] args)
{
DynamicSample dynamicSample = new DynamicSample ();
// Obtain DynamicSample through reflection
Var add = dynamicSample. GetType (). GetMethod ("Add ");
Stopwatch watch = new Stopwatch ();
Watch. Start ();
For (int I = 0; I <100000; I ++)
{
Int re = (int) add. Invoke (dynamicSample, new object [] {1, 2 });
}
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds); // about 200 milliseconds
Console. Read ();
}
}
Public class DynamicSample
{
Public string Name {get; set ;}
Public int Add (int a, int B)
{
Return a + B;
}
}
I tried it several times and it took about 200 milliseconds. Then we use dynamic for reflection to see how the performance works.
Class Program
{
Static void Main (string [] args)
{
Dynamic dynamicSample = new DynamicSample ();
Stopwatch watch = new Stopwatch ();
Watch. Start ();
For (int I = 0; I <100000; I ++)
{
Int re = dynamicSample. Add (1, 2 );
}
Watch. Stop ();
Console. WriteLine (watch. ElapsedMilliseconds); // about 50 milliseconds
Console. Read ();
}
}
Public class DynamicSample
{
Public string Name {get; set ;}
Public int Add (int a, int B)
{
Return a + B;
}
}
Not only is the Code reduced, but the performance also increases by an order of magnitude. We recommend that you use dynamic attributes for reflection!