I\'m using RedGate to do some performance evaluation. I notice dynamically creating an instance using Activator.CreateInstance (with two constructor parameters
Don't forget about DynamicMethod
Here's example how to create new instance thru default constructor
public static ObjectActivator CreateCtor(Type type)
{
if (type == null)
{
throw new NullReferenceException("type");
}
ConstructorInfo emptyConstructor = type.GetConstructor(Type.EmptyTypes);
var dynamicMethod = new DynamicMethod("CreateInstance", type, Type.EmptyTypes, true);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Nop);
ilGenerator.Emit(OpCodes.Newobj, emptyConstructor);
ilGenerator.Emit(OpCodes.Ret);
return (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator));
}
public delegate object ObjectActivator();
here's more about performance comparison
Measuring InvokeMember... 1000000 iterations in 1.5643784 seconds.
Measuring MethodInfo.Invoke... 1000000 iterations in 0.8150111 seconds.
Measuring DynamicMethod... 1000000 iterations in 0.0330202 seconds.
Measuring direct call... 1000000 iterations in 0.0136752 seconds.