I'm trying to cut back on the performance costs of calling Activator.CreateInstance() on each iteration of the following loop (simplified):
foreach (DataRow dr in chunk.Rows)
{
var objectToInsert = Activator.CreateInstance(type);
}
Based on what I've read the best way to go about this would be to compile a delegate and cache it. This would slow things down on the first iteration (while the delegate is being built) but would greatly improve performance on subsequent iterations. This acceptable since I'm iterating an upwards of a 1000 times. To further complicate matters I'm executing this loop in parallel so whatever caching mechanism will have to be thread safe (ConcurentDictionary). Making the method the loop is in into a generic isn't possible since the type I'm passing into Activator.CreateInstance() is determined by a choice made by the user through a GUI and passed to my function. For some reference here is the method signature:
public static void InsertByTable(IEnumerable<DataTable> chunkedTable, Type type)
So I want to do something sort of like this (this is pseudo code):
private static readonly ConcurrentDictionary<Type, Func<object>> CachedConstructors =
new ConcurrentDictionary<Type, Func<object>>();
private static object CreateInstance(Type type)
{
if (type == null)
return;
var constructor = CachedConstructors.GetOrAdd(type, BuildInstance);
constructor(type);
}
private static Func<Type> BuildInstance(Type type)
{
}
But I'm kind of at a loss how to actually build the expression or even if this is the right approach.