Skip to content

Instantly share code, notes, and snippets.

@kkozmic
Created November 11, 2009 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkozmic/232042 to your computer and use it in GitHub Desktop.
Save kkozmic/232042 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//let the JITter kick in
TestNonGenericAsIsNow(1);
TestGenericAsCouldBe(1);
//go with the actual test
var limit = 100000;
TestNonGenericAsIsNow(limit);
TestGenericAsCouldBe(limit);
Console.Read();
}
private static void TestNonGenericAsIsNow(int limit)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < limit; i++)
{
var fooBar = new FooBar();
var barFoo = new BarFoo();
var inv1 = new InvocationBarFoo(barFoo, "");
var inv2 = new InvocationFooBar(fooBar, 0);
inv1.Invoke();
inv2.Invoke();
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
private static void TestGenericAsCouldBe(int limit)
{
var methodFooBar = typeof(FooBar).GetMethod("Foo");
var methodBarFoo = typeof(BarFoo).GetMethod("Foo");
var sw = Stopwatch.StartNew();
// create open instance method delegates
var delegateFooBar = Delegate.CreateDelegate(typeof(Func<FooBar, int, string>), methodFooBar) as Func<FooBar, int, string>;
var delegateBarF0o = Delegate.CreateDelegate(typeof(Func<BarFoo, string, int>), methodBarFoo) as Func<BarFoo, string, int>;
for (int i = 0; i < limit; i++)
{
var fooBar = new FooBar();
var barFoo = new BarFoo();
var inv1 = new GenericInvocation<int, string, FooBar>(fooBar, 0, delegateFooBar);
var inv2 = new GenericInvocation<string, int, BarFoo>(barFoo, "", delegateBarF0o);
inv1.Invoke();
inv2.Invoke();
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
}
}
public class InvocationFooBar
{
private FooBar foo;
private string result;
private int param;
public InvocationFooBar(FooBar foo, int param)
{
this.foo = foo;
}
public void Invoke()
{
result = foo.Foo(param);
}
}
public class GenericInvocation<TIn, TOut, TTarget>
{
private TTarget foo;
private TOut result;
private TIn param;
private Func<TTarget, TIn, TOut> action;
public GenericInvocation(TTarget target, TIn param, Func<TTarget, TIn, TOut> action)
{
this.foo = target;
this.param = param;
this.action = action;
}
public void Invoke()
{
result = action(foo, param);
}
}
public class InvocationBarFoo
{
private BarFoo foo;
private int result;
private string param;
public InvocationBarFoo(BarFoo foo, string param)
{
this.foo = foo;
}
public void Invoke()
{
result = foo.Foo(param);
}
}
public class FooBar
{
public string Foo(int i)
{
return string.Empty;
}
}
public class BarFoo
{
public int Foo(string i)
{
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment