我正在从文件中读取和写入数据。文件中的数据可以是浮点数、双精度数、整数等。直到运行时才知道类型。我将文件中存储的数据类型称为 Tin。数据从 Tout 类型的数组中读取或写入。这种类型直到运行时也是未知的。
代码序列是这样的。在 Open 方法 Tin 和 Tout 已知的情况下,我们可以为已知的数据类型创建读写方法。
Open(...)
{
MethodInfo ReadMethod = typeof(...)GetMethod("ReadGeneric").MakeGenericMethod(new Type[] {typeof(Tin), typeof(Tout)}));
}
读写循环重复数百万次,并依靠反射来调用适当的方法,如下所示。
Read loop
{
var values = (Tout[])ReadMethod.Invoke(this,new object[]{index});
process ...
}
当使用性能分析器检查此代码时,我发现如果时间花在调用运行时读写方法上,则需要花费大量时间。
如何加快速度。
这将为您做任何事情,几乎与直接调用一样快。
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
public class FastMethodInfo
{
private delegate object ReturnValueDelegate(object instance, object[] arguments);
private delegate void VoidDelegate(object instance, object[] arguments);
public FastMethodInfo(MethodInfo methodInfo)
{
var instanceExpression = Expression.Parameter(typeof(object), "instance");
var argumentsExpression = Expression.Parameter(typeof(object[]), "arguments");
var argumentExpressions = new List<Expression>();
var parameterInfos = methodInfo.GetParameters();
for (var i = 0; i < parameterInfos.Length; ++i)
{
var parameterInfo = parameterInfos[i];
argumentExpressions.Add(Expression.Convert(Expression.ArrayIndex(argumentsExpression, Expression.Constant(i)), parameterInfo.ParameterType));
}
var callExpression = Expression.Call(!methodInfo.IsStatic ? Expression.Convert(instanceExpression, methodInfo.ReflectedType) : null, methodInfo, argumentExpressions);
if (callExpression.Type == typeof(void))
{
var voidDelegate = Expression.Lambda<VoidDelegate>(callExpression, instanceExpression, argumentsExpression).Compile();
Delegate = (instance, arguments) => { voidDelegate(instance, arguments); return null; };
}
else
Delegate = Expression.Lambda<ReturnValueDelegate>(Expression.Convert(callExpression, typeof(object)), instanceExpression, argumentsExpression).Compile();
}
private ReturnValueDelegate Delegate { get; }
public object Invoke(object instance, params object[] arguments)
{
return Delegate(instance, arguments);
}
}
.Net Framework 提供了大量的方法来动态调用方法。然而,它们在性能方面的表现并不相同,而且使用起来也不那么容易。
在 .Net Framework 的最新版本中,CreateDelegate 比 MethodInfo 调用高出 50 倍:
// The following should be done once since this does some reflection
var method = typeof (...).GetMethod("ReadGeneric");
// Here we create a Func that targets the instance of type which has the
// ReadGeneric method
var func = (Func<Tin, Tout[]>)_method.CreateDelegate(typeof(Func<Tin, Tout[]>), target);
// Func will be 50x faster than MethodInfo.Invoke
// use func as a standard Func like
// var tout = func(index);
查看我的这篇帖子以查看不同方法调用的基准测试