简体   繁体   中英

Improve object.GetType().GetProperties() and PropertyInfo.GetValue(object) performance

private int GenerateKey(T requestParams)
{
    foreach (PropertyInfo property in requestParams.GetType().GetProperties())
    {
            var propertyValue = property.GetValue(requestParams);
            // Do stuff with propertyValue
    }
    // ...
}

I have this code snippet that iterates through generic type properties and extracts each property's value. I know that Reflection can be a huge performance bottleneck and that it could be improved using delegates / DynamicMethod / ILGenerator. However its quite difficult for to grasp these. Example on how to utilize one of these methods would be awesome.

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
    }
    // ...
}

Solution using expression trees / delegates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM