我的项目涉及了很多反射。因此,我将委托缓存到字典中。问题在于,我选择使用MethodInfo作为字典键,我尝试使用查找方法,就像这样:
Func<T,R> LookUp(Func<T,R> m)
{
return (Func<T,R>)dict[m.Method];
}
//LookUp(MyCls.Method)
但是,经过一些测试,我发现使用函数地址喂给 LookUp 方法,也就是在动态创建过渡委托时,速度有点慢,确实非常慢:
class MyCls
{
public static void Operate(int whatever){ }
}
class MainClass
{
delegate void Doer<T>(T arg);
static Dictionary<MethodInfo,Delegate> _dict = new Dictionary<MethodInfo,Delegate>();
public static void Main (string[] args)
{
Action<int> dg = MyCls.Operate;
_dict[dg.Method] = Delegate.CreateDelegate(typeof(Action<int>),dg.Method);
//performance test
var start = Environment.TickCount;
for (int i = 0; i < 10000000; i++)
{
//LookUp(dg);//11
//LookUp<int>(MyCls.Operate);//1503
//new MyCls();//431
}
Console.WriteLine (Environment.TickCount-start);
}
static Action<T> LookUp<T>(Action<T> dg)
{
//should return (Action<T>)_dict[dg.Method];
return null;
}
所以问题是:为了提高性能,我应该改变我的方法并编写一些不安全的代码(C#是否支持函数指针?),还是有其他基于C#的解决方案适用于这种情况?
请帮帮我!