Skip to content

Instantly share code, notes, and snippets.

@pinscript
Created October 18, 2011 07:54
Show Gist options
  • Select an option

  • Save pinscript/1294843 to your computer and use it in GitHub Desktop.

Select an option

Save pinscript/1294843 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace ilab {
class Program {
private delegate string StringManipulator(string input);
static void Main(string[] args) {
new Program();
Console.WriteLine("Done");
Console.ReadLine();
}
public Program() {
var toLowerMethod = typeof(string).GetMethods().First(x => x.Name == "ToLower");
var toLowerIL = GetDelegate(toLowerMethod);
// Warmup
for (var i = 0; i < 1000; i++) {
IL(toLowerIL);
Reflection(toLowerMethod);
}
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 10000000; i++) {
IL(toLowerIL);
}
stopwatch.Stop();
Console.WriteLine("IL: {0} ms", stopwatch.ElapsedMilliseconds);
stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100000; i++) {
Reflection(toLowerMethod);
}
stopwatch.Stop();
Console.WriteLine("Reflection: {0} ms", stopwatch.ElapsedMilliseconds);
}
private static StringManipulator GetDelegate(MethodInfo method) {
var dynamicMethod = new DynamicMethod("StringManipulation", typeof(string), new[] { typeof(string) }, typeof(Program).Module);
var il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Callvirt, method);
il.Emit(OpCodes.Ret);
var func = dynamicMethod.CreateDelegate(typeof(StringManipulator)) as StringManipulator;
return func;
}
private static void IL(StringManipulator func) {
var result = func("aLeXAnDeR");
Debug.Assert(result.Equals("alexander"));
}
private static void Reflection(MethodInfo method) {
var result = method.Invoke("aLeXAnDeR", null);
Debug.Assert(result.Equals("alexander"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment