代码很简单,我就不多说了。直接贴代码和数据。
1:编译器调用
Code
UserCore core = new UserCore();
core.GetCount(50000279);
UserCore core = new UserCore();
core.GetCount(50000279);
2:反射
Code
Assembly classSampleAssembly = Assembly.LoadFrom(@"C:\SNSService\Snda.Qidian.SNS.DataCore.dll");
Type classSampleType = classSampleAssembly.GetType("Snda.Qidian.SNS.DataCore.UserCore");
object instance = Activator.CreateInstance(classSampleType);
object returnValue1 = classSampleType.InvokeMember("GetCount", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, instance, new object[] { 50000279 });
Assembly classSampleAssembly = Assembly.LoadFrom(@"C:\SNSService\Snda.Qidian.SNS.DataCore.dll");
Type classSampleType = classSampleAssembly.GetType("Snda.Qidian.SNS.DataCore.UserCore");
object instance = Activator.CreateInstance(classSampleType);
object returnValue1 = classSampleType.InvokeMember("GetCount", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, instance, new object[] { 50000279 });
3:优化后的反射
Code
Assembly assembly = Assembly.Load("Snda.Qidian.SNS.DataCore");
object ins = null;
Type HereType = null;
MethodInfo method = null;
foreach (Module m in assembly.GetModules())
{
{
if (string.Equals(t.Name, "UserCore"))
{
foreach (MethodInfo mInfo in t.GetMethods())
{
if (string.Equals(mInfo.Name, "GetCount"))
{
HereType = t;
method = mInfo;
break;
}
}
}
break;
}
break;
}
{
ins = assembly.CreateInstance(HereType.FullName);
}
object RetObject = method.Invoke(ins, new object[] { 50000279 });
Assembly assembly = Assembly.Load("Snda.Qidian.SNS.DataCore");
object ins = null;
Type HereType = null;
MethodInfo method = null;
//在模块上进行反射
foreach (Module m in assembly.GetModules())
{
foreach (Type t in m.GetTypes())
{
if (string.Equals(t.Name, "UserCore"))
{
foreach (MethodInfo mInfo in t.GetMethods())
{
if (string.Equals(mInfo.Name, "GetCount"))
{
HereType = t;
method = mInfo;
break;
}
}
}
if (method != null)
break;
}
if (method != null)
break;
}
if (!method.IsStatic)
{
ins = assembly.CreateInstance(HereType.FullName);
}
object RetObject = method.Invoke(ins, new object[] { 50000279 });
测试数据
B,C,D列为第1,2,3种方式运行100次耗费的时间
F,G,H列为第1,2,3种方式运行1次耗费的时间
最后一行为各种方法的平均数值。
大家有什么想法,欢迎拍砖。