Activator.CreateInstance Performance Alternative

前端 未结 3 1786
情话喂你
情话喂你 2020-12-07 22:34

I\'m using RedGate to do some performance evaluation. I notice dynamically creating an instance using Activator.CreateInstance (with two constructor parameters

3条回答
  •  甜味超标
    2020-12-07 23:04

    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.

提交回复
热议问题