【问题标题】:Improve object.GetType().GetProperties() and PropertyInfo.GetValue(object) performance提高 object.GetType().GetProperties() 和 PropertyInfo.GetValue(object) 性能
【发布时间】:2019-05-21 05:08:56
【问题描述】:
private int GenerateKey(T requestParams)
{
    foreach (PropertyInfo property in requestParams.GetType().GetProperties())
    {
            var propertyValue = property.GetValue(requestParams);
            // Do stuff with propertyValue
    }
    // ...
}

我有这段代码 sn-p 遍历泛型类型属性并提取每个属性的值。我知道反射可能是一个巨大的性能瓶颈,并且可以使用委托/DynamicMethod/ILGenerator 对其进行改进。然而,掌握这些是相当困难的。有关如何使用其中一种方法的示例将非常棒。

【问题讨论】:

  • 只有当你真的遇到性能问题时,你才应该为此烦恼。这样做prematurely is poor evil
  • GenerateKey 方法是否为相同的T requestParams 创建相同的密钥?
  • @Emrah Süngü 是的
  • @Lemanas 你能发布更完整的代码吗?您能否提及您的方法的用例。你会用同一个 T 类的不同实例多次调用这个方法吗?如果你打算很少使用这个方法,你不需要优化这个方法

标签: c# reflection delegates system.reflection dynamicmethod


【解决方案1】:
private PropertyInfo[] Properties { get; }
private Func<T, PropertyInfo, object> ExecutableGetter { get; }

public Constructor()
{
      Properties = typeof(T).GetProperties();
      Expression<Func<T, PropertyInfo, object>> getter = (tParams, property) => property.GetValue(tParams);
      ExecutableGetter = getter.Compile();
}

private int GenerateKey(T requestParams)
{
    foreach (PropertyInfo property in Properties)
    {
            var propertyValue = ExecutableGetter(requestParams, property);
            // Do stuff with propertyValue
    }
    // ...
}

使用表达式树/委托的解决方案

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2021-12-18
    • 2011-05-07
    相关资源
    最近更新 更多