Search code examples
c#reflectiondelegatessystem.reflectiondynamicmethod

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.


Solution

  • 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