mercredi 13 décembre 2017

Static reflection benefits

Besides using strongly types instead magic strings, do I have any extra benefit if I use static reflection over dynamic.

For example, in the following four simple methods, I've measured the execution time in four scenarios:

  1. Reading an attribute using dynamic reflection
  2. Reading an attribute using static reflection
  3. Reading an attribute and getting the property value using dynamic reflection
  4. Reading an attribute and getting the property value using static reflection

    public bool IsPropertyObsolete<TModel>(string propertyName)
    {
        PropertyInfo prop = typeof(TModel).GetProperty(propertyName);
        var attr = prop.GetCustomAttribute<ObsoleteAttribute>();
        return attr != null;
    }
    
    public bool IsPropertyObsolete<TModel>(Expression<Func<TModel, object>> expressionProperty)
    {
        var bodyExpr = expressionProperty.Body as MemberExpression;
        var attri = bodyExpr.Member.GetCustomAttribute<ObsoleteAttribute>();
        return attri != null;
    }
    
    public string GetDataMember<TModel>(string propertyName, TModel model)
    {
        PropertyInfo prop = typeof(TModel).GetProperty(propertyName);
        var attri = prop.GetCustomAttribute<DataMemberAttribute>();
        var value = prop.GetValue(model).ToString();
        return string.Format("Name: {0}, Value: {1}", attri.Name, value);
    }
    
    public string GetDataMember<TModel>(Expression<Func<TModel, object>> expressionProperty, TModel model)
    {
        var bodyExpr = expressionProperty.Body as MemberExpression;
        var attri = bodyExpr.Member.GetCustomAttribute<DataMemberAttribute>();
        var value = expressionProperty.Compile()(model);
        return string.Format("Name: {0}, Value: {1}", attri.Name, value);
    }
    
    

Results:

  1. 0,0176198610746356 ms
  2. 0,0194476837339746 ms
  3. 0,0153574448912522 ms
  4. 0,14013698580629 ms

The first three scenarios threw similar results, but in the fourth, because we have to compile the expression, the differences were remarkable. Static reflection took About 10 times more.

Am I right if I say that static reflection is good as long as we do not need to compile the expression? Is it only a good choice if I use reflection to examine the class and not its content?





Aucun commentaire:

Enregistrer un commentaire