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:
- Reading an attribute using dynamic reflection
- Reading an attribute using static reflection
- Reading an attribute and getting the property value using dynamic reflection
-
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:
- 0,0176198610746356 ms
- 0,0194476837339746 ms
- 0,0153574448912522 ms
- 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