using System;
using System.Reflection;
using System.Reflection.Emit;
namespace ReflectorOptimization.Common
{
///<summary>/// 反射優化,反射發出(Emit)///</summary>publicclass FastMethodInvoker
{
publicdelegateobjectFastInvokeHandler(object target, object[] paramters);
privatestaticobjectInvokeMethod(FastInvokeHandler invoke, object target, paramsobject[] paramters)
{
return invoke(null, paramters);
}
publicstatic FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
{
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
ILGenerator il = dynamicMethod.GetILGenerator();
ParameterInfo[] ps = methodInfo.GetParameters();
Type[] paramTypes = new Type[ps.Length];
for (int i = 0; i < paramTypes.Length; i++)
{
if (ps[i].ParameterType.IsByRef)
paramTypes[i] = ps[i].ParameterType.GetElementType();
else
paramTypes[i] = ps[i].ParameterType;
}
LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];
for (int i = 0; i < paramTypes.Length; i++)
{
locals[i] = il.DeclareLocal(paramTypes[i], true);
}
for (int i = 0; i < paramTypes.Length; i++)
{
il.Emit(OpCodes.Ldarg_1);
EmitFastInt(il, i);
il.Emit(OpCodes.Ldelem_Ref);
EmitCastToReference(il, paramTypes[i]);
il.Emit(OpCodes.Stloc, locals[i]);
}
if (!methodInfo.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
}
for (int i = 0; i < paramTypes.Length; i++)
{
if (ps[i].ParameterType.IsByRef)
il.Emit(OpCodes.Ldloca_S, locals[i]);
else
il.Emit(OpCodes.Ldloc, locals[i]);
}
if (methodInfo.IsStatic)
il.EmitCall(OpCodes.Call, methodInfo, null);
else
il.EmitCall(OpCodes.Callvirt, methodInfo, null);
if (methodInfo.ReturnType == typeof(void))
il.Emit(OpCodes.Ldnull);
else
EmitBoxIfNeeded(il, methodInfo.ReturnType);
for (int i = 0; i < paramTypes.Length; i++)
{
if (ps[i].ParameterType.IsByRef)
{
il.Emit(OpCodes.Ldarg_1);
EmitFastInt(il, i);
il.Emit(OpCodes.Ldloc, locals[i]);
if (locals[i].LocalType.IsValueType)
il.Emit(OpCodes.Box, locals[i].LocalType);
il.Emit(OpCodes.Stelem_Ref);
}
}
il.Emit(OpCodes.Ret);
FastInvokeHandler invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
return invoder;
}
privatestaticvoidEmitCastToReference(ILGenerator il, System.Type type)
{
if (type.IsValueType)
{
il.Emit(OpCodes.Unbox_Any, type);
}
else
{
il.Emit(OpCodes.Castclass, type);
}
}
privatestaticvoidEmitBoxIfNeeded(ILGenerator il, System.Type type)
{
if (type.IsValueType)
{
il.Emit(OpCodes.Box, type);
}
}
privatestaticvoidEmitFastInt(ILGenerator il, intvalue)
{
switch (value)
{
case -1:
il.Emit(OpCodes.Ldc_I4_M1);
return;
case0:
il.Emit(OpCodes.Ldc_I4_0);
return;
case1:
il.Emit(OpCodes.Ldc_I4_1);
return;
case2:
il.Emit(OpCodes.Ldc_I4_2);
return;
case3:
il.Emit(OpCodes.Ldc_I4_3);
return;
case4:
il.Emit(OpCodes.Ldc_I4_4);
return;
case5:
il.Emit(OpCodes.Ldc_I4_5);
return;
case6:
il.Emit(OpCodes.Ldc_I4_6);
return;
case7:
il.Emit(OpCodes.Ldc_I4_7);
return;
case8:
il.Emit(OpCodes.Ldc_I4_8);
return;
}
if (value > -129 && value < 128)
{
il.Emit(OpCodes.Ldc_I4_S, (SByte)value);
}
else
{
il.Emit(OpCodes.Ldc_I4, value);
}
}
}
}
Program.cs
using ReflectorOptimization.Common;
using System;
using System.Diagnostics;
using System.Reflection;
namespace ReflectorOptimization.Test
{
internalclass Program
{
privatestaticvoidMain(string[] args)
{
Type t = typeof(Person);
MethodInfo methodInfo = t.GetMethod("Say");
Person person = new Person();
string word = "hello";
Person p = null;
object[] param = newobject[] { word, p, 3 };
int testCount = 100000;//測試次數#region 傳統方式反射try
{
Stopwatch watch = new Stopwatch();
watch.Start();
for (int i = 0; i < testCount; i++)
{
methodInfo.Invoke(person, param);
}
watch.Stop();
Console.WriteLine(testCount.ToString() + " times invoked by Reflection:" + watch.ElapsedMilliseconds + "ms");
}
catch (System.Exception ex)
{ }
#endregion 傳統方式反射#region 快速反射try
{
Stopwatch watch1 = new Stopwatch();
FastMethodInvoker.FastInvokeHandler fastInvoker = FastMethodInvoker.GetMethodInvoker(methodInfo);
watch1.Start();
for (int i = 0; i < testCount; i++)
{
fastInvoker(person, param);
}
watch1.Stop();
Console.WriteLine(testCount.ToString() + " times invoked by FastInvoke: " + watch1.ElapsedMilliseconds + "ms");
}
catch (System.Exception ex)
{
Console.WriteLine("快速反射 錯誤:" + ex.Message);
}
#endregion 快速反射#region 直接呼叫try
{
Stopwatch watch2 = new Stopwatch();
watch2.Start();
for (int i = 0; i < testCount; i++)
{
person.Say(ref word, out p, 3);
}
watch2.Stop();
Console.WriteLine(testCount.ToString() + " times invoked by DirectCall: " + watch2.ElapsedMilliseconds + "ms");
}
catch (System.Exception ex)
{
Console.WriteLine("直接呼叫 錯誤:" + ex.Message);
}
#endregion 直接呼叫
Console.ReadKey();
}
}
publicclass Person
{
publicvoidSay(refstring word, out Person p, int avi)
{
word = "ttt" + avi.ToString();
p = new Person();
//throw new System.Exception("出錯了哦");
}
}
}