MethodInfo.Invoke性能问题 [英] MethodInfo.Invoke performance issue

查看:1109
本文介绍了MethodInfo.Invoke性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读,写数据和从文件中。文件中的数据可以是花车,双打,整数等类型不知道,直到运行时。我将参照存储该文件作为锡中的数据类型。数据读入或类型的吹捧阵列写的。这种类型的也太不知道,直到运行时。

I am reading and writing data to and from a file. The data in the file can be floats, doubles, ints etc. The type is not known until runtime. I will refer to data type stored in the file as Tin. Data is read into or written from arrays of type Tout. This type too is not known until runtime.

在code顺序是这样的。在Open方法锡和吹捧是已知的,我们可以创建读写已知数据类型的方法。

The code sequence is something like this. In the Open method Tin and Tout are known, we can create read and write methods for the known data types.

Open(...)
{
   MethodInfo ReadMethod = typeof(...)GetMethod("ReadGeneric").MakeGenericMethod(new Type[] {typeof(Tin), typeof(Tout)}));
}

的读写循环重复数百万次,并依靠反射调用适当的方法如下所示。

The read write loops repeat millions of times and rely on reflection to invoke the appropriate methods as shown below.

Read loop
{
   var values = (Tout[])ReadMethod.Invoke(this,new object[]{index});
   process ...
}

在使用性能分析器,我觉得将c collosal量,如果时间仅仅花了调用运行时的读写方法研究这个code。

When examining this code using a performance profiler I find that c collosal amount if time is spent just invoking the runtime read write methods.

我如何加快这。

推荐答案

是的,这是由于这一事实,即反射API的几千倍比直接的方法调用速度较慢。还有一些有趣的技术来解决这个但是。退房乔恩斯基特的使用委托在文章缓存反射

Yes, this is due to the fact that the reflection API is thousands of times slower than direct method calls. There are some interesting techniques to work around this however. Check out Jon Skeet's article on using delegates to cache reflection.

有一个静态的设置成本,但一旦你做到这一点的时候调用委托多次就相当于虚拟的方法调用。

There is a static setup cost but once you have done that the time to invoke the delegate repeatedly is equivalent to virtual method calls.

也有一些 pre封装框架来达到同样的事情。

There are also some pre-packaged frameworks to achieve the same thing.

这篇关于MethodInfo.Invoke性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆