41
I'm trying to improve the performance of our application. We have a lot of Activator.CreateInstance calls that are causing some grief.
We instantiate a lot of classes based on an interface (ITabDocument) and after looking around I thought of using this code:
The code is no better (in fact marginally slower) than using the Activator.CreateInstance code we had.
public static Func<T> CreateInstance<T>(Type objType) where T : class, new()
{
var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + objType.Name, objType, null, objType);
ILGenerator ilGen = dynMethod.GetILGenerator();
ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes));
ilGen.Emit(OpCodes.Ret);
return (Func<T>)dynMethod.CreateDelegate(typeof(Func<T>));
}
I'm wondering why this is, all I'm doing is:
ITabDocument document = CreateInstance<ITabDocument>(Type.GetType("[Company].Something"));
Is there a better way of creating objects which would assist with the above? It's a little hard when you're not sure of the concrete type.