Long answer. Reflection is wonderful in many situations, terrible in some, but in almost all cases it is slow.
There are at least 4 different ways to set a property in .NET without the need to use reflection.
It seemed to me that I was demonstrating one of them: Using compiled expression trees. Note that constructing an expression is quite expensive, so it is very important to cache the delegate that it builds with it in the dictionary (for example):
Expression trees were introduced in .NET35 and are used for many things. Here I use them to create a setterter expression and then compile it into a delegate.
The example shows different terms for different cases, but here are my numbers: Check register (hard-coded): 0.02 s Reflection: 1.78 Expression tree: 0.06 s
using System; using System.Linq.Expressions; namespace DifferentPropertSetterStrategies { class TestClass { public string XY { get; set; } } class DelegateFactory { public static Action<object, object> GenerateSetPropertyActionForControl( ) { return (inst, val) => ((TestClass) inst).XY = (string) val; } public static Action<object, object> GenerateSetPropertyActionWithReflection( Type type, string property ) { var propertyInfo = type.GetProperty(property); return (inst, val) => propertyInfo.SetValue (inst, val, null); } public static Action<object,object> GenerateSetPropertyActionWithLinqExpression ( Type type, string property ) { var propertyInfo = type.GetProperty(property); var propertyType = propertyInfo.PropertyType; var instanceParameter = Expression.Parameter(typeof(object), "instance"); var valueParameter = Expression.Parameter(typeof(object), "value"); var lambda = Expression.Lambda<Action<object, object>> ( Expression.Assign ( Expression.Property (Expression.Convert (instanceParameter, type), propertyInfo), Expression.Convert(valueParameter, propertyType)), instanceParameter, valueParameter ); return lambda.Compile(); } } static class Program { static void Time ( string tag, object instance, object value, Action<object, object > action ) {
FuleSnabel
source share