public void CompareFormatterServicesActivationAndDynamicFactoryMethod() { int iterations = 1000000; Stopwatch stopwatch1 = new Stopwatch(); Stopwatch stopwatch2 = new Stopwatch(); ConstructorInfo constructor = typeof(BenchmarkObject).GetConstructor(new Type[] { typeof(int), typeof(string) }); FactoryMethod factoryMethod = DynamicMethodFactory.CreateFactoryMethod(constructor); for (int index = 0; index < iterations; index++) { stopwatch1.Start(); BenchmarkObject mock1 = (BenchmarkObject)FormatterServices.GetSafeUninitializedObject(typeof(BenchmarkObject)); constructor.Invoke(mock1, new object[] { 42, "foobar" }); stopwatch1.Stop(); stopwatch2.Start(); BenchmarkObject mock2 = (BenchmarkObject)factoryMethod(42, "foobar"); stopwatch2.Stop(); } Console.WriteLine("{0:0,0} iterations:", iterations); Console.WriteLine("FormatterServices/Constructor.Invoke: {0:0,0} ms", stopwatch1.ElapsedMilliseconds); Console.WriteLine("Dynamic FactoryMethod: {0:0,0} ms", stopwatch2.ElapsedMilliseconds); Console.WriteLine("Speedup: {0:f}x", ((double)stopwatch1.ElapsedMilliseconds / (double)stopwatch2.ElapsedMilliseconds)); }
/*----------------------------------------------------------------------------------------*/ #region Public Methods /// <summary> /// Creates a new instance of a type by calling the injector's constructor. /// </summary> /// <param name="arguments">The arguments to pass to the constructor.</param> /// <returns>A new instance of the type associated with the injector.</returns> public object Invoke(params object[] arguments) { if (_factoryMethod == null) _factoryMethod = DynamicMethodFactory.CreateFactoryMethod(Member); return _factoryMethod.Invoke(arguments); }