Performance Test — Dynamic method invocation in C# 4

By now you would have no doubt heard about the new dynam­ic type in C# 4 and how it has changed the way you write interop code in C#. As impressed as I am by it, I have been won­der­ing just how much (if any) of a per­for­mance hit we’d have to pay to move away from the fast but strict type sys­tem we have had so far.

Since the very first release of the .Net frame­work we’ve had the abil­i­ty to invoke a method dynam­i­cal­ly using reflec­tion, but this is SLOW, so what of the new dynam­ic type? With this in mind, I put togeth­er a quick test to see how the three ways of invok­ing a method dif­fer in per­for­mance:

class Pro­gram
{
sta­t­ic void Main(string[] args)
{
con­st int max­At­tempt = 1000000;
var stop­watch = new Stop­watch();

#region Nor­mal Invo­ca­tion
var prog = new Pro­gram();
stopwatch.Start();
for (int i = 0; i max­At­tempt; i++) { prog.Foo(); } stopwatch.Stop(); Console.WriteLine(“Normal Invo­ca­tion took {0} mil­lisec­onds”, stopwatch.ElapsedMilliseconds); #endre­gion #region Using Reflec­tion Type t = prog.GetType(); stopwatch.Restart(); for (int i = 0; i max­At­tempt; i++) { t.InvokeMember(“Foo”, BindingFlags.InvokeMethod, null, prog, new object[] { }); } stopwatch.Stop(); Console.WriteLine(“Using reflec­tion took {0} mil­lisec­onds”, stopwatch.ElapsedMilliseconds); #endre­gion #region Dynam­ic Invo­ca­tion dynam­ic dynam­icProg = prog; stopwatch.Restart(); for (int i = 0; i max­At­tempt; i++) { dynamicProg.Foo(); } stopwatch.Stop(); Console.WriteLine(“Dynamic Invo­ca­tion took {0} mil­lisec­onds”, stopwatch.ElapsedMilliseconds); #endre­gion Console.ReadKey(); } pub­lic void Foo() {} } [/code] The result? Well, unsur­pris­ing­ly nor­mal invo­ca­tion wins hands down, but invok­ing a method on the dynam­ic type is sur­pris­ing­ly fast com­pared to invok­ing a method using reflec­tion! image