Skip to content

Instantly share code, notes, and snippets.

@danielwertheim
Created August 8, 2013 19:50
Show Gist options
  • Save danielwertheim/6188062 to your computer and use it in GitHub Desktop.
Save danielwertheim/6188062 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class FakeController
{
public Dictionary<string, Action<object>> delegates1;
public Dictionary<string, Action<FakeController>> delegates2;
public Dictionary<string, MethodInfo> methodInfos;
public FakeController()
{
this.delegates1 = new Dictionary<string, Action<object>>();
this.delegates2 = new Dictionary<string, Action<FakeController>>();
this.methodInfos = new Dictionary<string, MethodInfo>();
foreach (var mi in this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public))
{
if (mi.DeclaringType == this.GetType())
{
this.methodInfos.Add(mi.Name, mi);
this.delegates1.Add(mi.Name, this.CreateFoo1(mi));
this.delegates2.Add(mi.Name, this.CreateFoo2(mi));
}
}
}
public void Apa()
{
//Här händer inte mycket
}
private Action<object> CreateFoo1(MethodInfo m)
{
var objExpr = Expression.Parameter(typeof(object), "theItem");
var castedObjExpr = Expression.Convert(objExpr, m.DeclaringType);
return Expression.Lambda<Action<object>>(
Expression.Call(castedObjExpr, m), new[] { objExpr }).Compile();
}
private Action<FakeController> CreateFoo2(MethodInfo m)
{
var objExpr = Expression.Parameter(m.DeclaringType, "theItem");
return Expression.Lambda<Action<FakeController>>(
Expression.Call(objExpr, m), new[] { objExpr }).Compile();
}
}
class Program
{
static void Main(string[] args)
{
var o = new FakeController();
//warmup
for (var i = 0; i < 100; i++)
{
foreach (var m in o.methodInfos)
{
m.Value.Invoke(o, new object[] { });
}
foreach (var m in o.delegates1)
{
m.Value.Invoke(o);
}
foreach (var m in o.delegates2)
{
m.Value.Invoke(o);
}
}
//Time MethodInfo
var t = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
o.methodInfos["Apa"].Invoke(o, new object[] { });
}
t.Stop();
Console.WriteLine("MethodInfo: " + t.Elapsed.TotalMilliseconds);
//Time Delegates
t.Restart();
for (int i = 0; i < 1000000; i++)
{
o.delegates1["Apa"].Invoke(o);
}
t.Stop();
Console.WriteLine("Delegate1: " + t.Elapsed.TotalMilliseconds);
t.Restart();
for (int i = 0; i < 1000000; i++)
{
o.delegates2["Apa"].Invoke(o);
}
t.Stop();
Console.WriteLine("Delegate2: " + t.Elapsed.TotalMilliseconds);
Console.WriteLine("Done...");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment