using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection.Emit;
using System.Runtime.Serialization;
namespace ConsoleApplication1
{
public class Program
{
public static void Main()
{
const int iterations = 10000;
var functions = new Dictionary<string, Func<Created>>();
functions.Add("new", () => new Created());
functions.Add("Activator", () => (Created)Activator.CreateInstance(typeof(Created)) );
functions.Add("constructorInfo.Invoke", () =>
{
var constructorInfo = typeof(Created).GetConstructor(Type.EmptyTypes);
return (Created) constructorInfo.Invoke(null);
});
functions.Add("constructorInfo.Invoke GetUninitializedObject", () =>
{
var constructorInfo = typeof(Created).GetConstructor(Type.EmptyTypes);
object o = FormatterServices.GetUninitializedObject(typeof(Created));
return (Created)constructorInfo.Invoke(o, null);
});
functions.Add("DynamicMethod", () =>
{
var type = typeof (Created);
var constructorInfo = typeof(Created).GetConstructor(Type.EmptyTypes);
var dm = new DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(Program).Module, true);
ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Newobj, constructorInfo);
ilgen.Emit(OpCodes.Ret);
return (Created)dm.Invoke(null, null);
});
functions.Add("DynamicMethod with Delegate", () =>
{
var type = typeof (Created);
var constructorInfo = typeof(Created).GetConstructor(Type.EmptyTypes);
var dm = new DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(Program).Module, true);
ILGenerator ilgen = dm.GetILGenerator();
ilgen.Emit(OpCodes.Nop);
ilgen.Emit(OpCodes.Newobj, constructorInfo);
ilgen.Emit(OpCodes.Ret);
return ((Func<Created>)dm.CreateDelegate(typeof(Func<Created>)))();
});
functions.Add("Expression", () =>
{
var constructorInfo = typeof(Created).GetConstructor(Type.EmptyTypes);
var newExp = Expression.New(constructorInfo);
var lambda = Expression.Lambda(typeof(Func<Created>), newExp);
return ((Func<Created>) lambda.Compile())();
});
foreach (var item in functions)
{
var watch = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
item.Value();
}
Console.WriteLine("{1} {0}",item.Key, watch.Elapsed);
}
Console.ReadLine();
}
}
public class Created
{
public int Num;
public string Name;
public Created(int num, string name)
{
Num = num;
Name = name;
}
public Created()
{
Num = 1;
Name = "Created";
}
}
}