I have a stream of thousands of data which I need to transform and add to a list. The transformation happens through the reflection similar to following
_myObservable.Subscribe(d => {
PropertyInfo[] props = d.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propValDict = props.ToDictionary(prop => prop.Name, prop => prop.GetValue(d, null));
myList.Add(propValDict);
});
// Datatype of d is determined during runtime and there are only 8 possibilities of the type
But this approach is slowing down the performance and I expect the use of reflection might be the reason. I am thinking of improving the performance by some other means.
Suggestions seem to point at use of Expression trees, create compiled lambda (Func<object,Dictionary<string, object>>) and store it in a lookup dictionary before hand.
//Foreach possibleType in PossibleTypes, Do below
PropertyInfo[] props = possibleType.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
var rootParam = Expression.Parameter(typeof(object), "d");
var param = Expression.Parameter(typeof(PropertyInfo), "prop");
var propertyFirst = Expression.Property(param, "Name");
var param2 = Expression.Parameter(typeof(PropertyInfo), "prop");
var callMethod = Expression.Call(param2, typeof(PropertyInfo).GetMethod(nameof(PropertyInfo.GetValue), new Type[] { typeof(object) }), rootParam);
var pro = Expression.Parameter(typeof(Array), "props");
var toDict = Expression.Invoke(pro, propertyFirst, callMethod);
var lambda = Expression.Lambda<Func<object, Dictionary<string, object>>>(toDict, rootParam);
var compiled = lambda.Compile();
I am having trouble to invoke ToDictionary of Enumerable class There is something which I am missing with this approach or Will this really improve performance.
Please help...