using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection.Emit; namespace CreateInstanceTest { class TestClass { } class ClassFactory where T : new() { public static T Create() { return new T(); } } class Program { static void CreateInstances(int instances, Action report) { var sw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < instances; i++) { var t = new TestClass(); } sw.Stop(); report("new TestClass();", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < instances; i++) { var t = Activator.CreateInstance(); } sw.Stop(); report("Activator.CreateInstance();", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < instances; i++) { var t = ClassFactory.Create(); } sw.Stop(); report("ClassFactory.Create();", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < instances; i++) { var t = Activator.CreateInstance(typeof(TestClass)); } sw.Stop(); report("Activator.CreateInstance(typeof(TestClass))", sw.Elapsed); sw.Reset(); sw.Start(); var ctor = typeof(TestClass).GetConstructor(Type.EmptyTypes); for (int i = 0; i < instances; i++) { var t = ctor.Invoke(null); } sw.Stop(); report("ctor.Invoke(null)", sw.Elapsed); sw.Reset(); sw.Start(); var dynMethod = new DynamicMethod("blabla", typeof(TestClass), Type.EmptyTypes, typeof(TestClass)); var ilGen = dynMethod.GetILGenerator(); ilGen.Emit(OpCodes.Newobj, typeof(TestClass).GetConstructor(Type.EmptyTypes)); ilGen.Emit(OpCodes.Ret); var creator = (Func)dynMethod.CreateDelegate(typeof(Func)); for (int i = 0; i < instances; i++) { var t = creator(); } sw.Stop(); report("creator()", sw.Elapsed); sw.Reset(); sw.Start(); var lambdaCreator = (Func)System.Linq.Expressions.Expression.Lambda(System.Linq.Expressions.Expression.TypeAs(System.Linq.Expressions.Expression.New(typeof(TestClass)), typeof(object))).Compile(); for (int i = 0; i < instances; i++) { var t = lambdaCreator(); } sw.Stop(); report("lambdaCreator()", sw.Elapsed); } static void Main(string[] args) { CreateInstances(1024 * 1024, (m, t) => Console.WriteLine("{0}:\t{1} ms", m, t.Ticks / 10000.0)); //CreateInstances(1024 * 1024, (m, t) => Console.WriteLine("{0}{1}1,0", m, t.Ticks / 10000.0)); Console.Read(); } } }