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

Enjoy what you’re reading? Subscribe to my newsletter and get more content on AWS and serverless technologies delivered straight to your inbox.


Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.


Check out my new course, Complete Guide to AWS Step Functions.

In this course, we’ll cover everything you need to know to use AWS Step Functions service effectively. Including basic concepts, HTTP and event triggers, activities, design patterns and best practices.

Get Your Copy