Performance Test – Dynamic method invocation in C# 4

By now you would have no doubt heard about the new dynamic 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 wondering just how much (if any) of a performance hit we’d have to pay to move away from the fast but strict type system we have had so far.

Since the very first release of the .Net framework we’ve had the ability to invoke a method dynamically using reflection, but this is SLOW, so what of the new dynamic type? With this in mind, I put together a quick test to see how the three ways of invoking a method differ in performance:

class Program
{
static void Main(string[] args)
{
const int maxAttempt = 1000000;
var stopwatch = new Stopwatch();

#region Normal Invocation
var prog = new Program();
stopwatch.Start();
for (int i = 0; i maxAttempt; i++) { prog.Foo(); } stopwatch.Stop(); Console.WriteLine("Normal Invocation took {0} milliseconds", stopwatch.ElapsedMilliseconds); #endregion #region Using Reflection Type t = prog.GetType(); stopwatch.Restart(); for (int i = 0; i maxAttempt; i++) { t.InvokeMember("Foo", BindingFlags.InvokeMethod, null, prog, new object[] { }); } stopwatch.Stop(); Console.WriteLine("Using reflection took {0} milliseconds", stopwatch.ElapsedMilliseconds); #endregion #region Dynamic Invocation dynamic dynamicProg = prog; stopwatch.Restart(); for (int i = 0; i maxAttempt; i++) { dynamicProg.Foo(); } stopwatch.Stop(); Console.WriteLine("Dynamic Invocation took {0} milliseconds", stopwatch.ElapsedMilliseconds); #endregion Console.ReadKey(); } public void Foo() {} } [/code] The result? Well, unsurprisingly normal invocation wins hands down, but invoking a method on the dynamic type is surprisingly fast compared to invoking a method using reflection! image

  • Val

    good job !
    saved me time from testing this myself

  • Val

    btw to make the relection a lot faster use this:

    #region Using Val Reflection
    Type tv = prog.GetType();
    stopwatch.Restart();
    var method = tv.GetMethod(“Foo”);
    for (int i = 0; i < maxAttempt; i++)
    {
    method.Invoke(prog, new object[] { });
    }
    stopwatch.Stop();
    Console.WriteLine("Using val reflection took {0} milliseconds",
    stopwatch.ElapsedMilliseconds);
    #endregion

  • theburningmonk

    @Val

    nice one, what sorta numbers did you get with invoking the method using the MethodInfo vs InvokeMember?

  • Pingback: Dynamics | Various Talks()