


















反射的性能差是一个公认的事实.而最耗性能的还是根据程序集获取要调用的对象,而在对象里搜索要调用的方法所耗性能到不不是很多,如果对象里的方法不是特别的多,而去可以指定相关参数提高搜索的效率,比如BindingFlags,Binder.
如果将对象的类型和方法属性进行一下存储,性能方法应该会得到改观.
简单的做了下测试:
class Program
{
static IDictionary<string , Type> typeList = new Dictionary<string , Type>();static IDictionary<string , MethodInfo> methodList = new Dictionary<string , MethodInfo>();static void Main ( string[] args )
{
int iBegin = Environment.TickCount;
for ( int i = 0 ; i < 1000 ; i++ )
{
Test1( "Test.TestClass,Test" );
Test1( "Test1.Class1,Test1" );
}
Console.WriteLine( "普通:{0}" , Environment.TickCount - iBegin );
GC.Collect();
iBegin = Environment.TickCount;
for ( int i = 0 ; i < 1000 ; i++ )
{
Test2( "Test.TestClass,Test" );
Test2( "Test1.Class1,Test1" );
}
Console.WriteLine( "存储Type:{0}" , Environment.TickCount - iBegin );
GC.Collect();
iBegin
= Environment.TickCount;
Console.ReadLine();
}
instance
= Activator.CreateInstance( type , null );instance
= Activator.CreateInstance( type , null );int val = 0;
public Class1 ( int val )
{
this.val = val;
}
public string GetValue ()
{
return string.Format( "the value is {0}" , val );
}
public int Add ( int a , int b )
{
return a + b;
}
为了测试,上面2个类里都加了几个方法(只是定义,并没有具体的实现代码).
测试了下不进行任何处理,时间都在130左右波动,对Type进行存储,时间在32左右,基本上没什么波幅,而对Type和MethodInfo进行存储时间维持在31.
看来这样处理下对性能的改善还是起到了作用.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。