Performance Test – Delegates vs Methods

Quite some time ago I was asked to cov­er a C# devel­op­er inter­view for one of my neigh­bour­ing teams, and on the sheet of ques­tions the orig­i­nal inter­view­er want­ed me to ask was this ques­tion:

Q. Why should you NEVER use del­e­gates?

I thought: “Well, at least I can rule myself out for the role!”

To my mind, if using del­e­gates com­pli­cates your code or make it less readable/maintainable then you shouldn’t use it, but to say NEVER to using del­e­gates? It just doesn’t make sense…

Puz­zled, I asked: “Why not?”

Because it’s an order of mag­ni­tude slow­er than using meth­ods”

Sounds like he’s had his fin­gers burnt in the past, but still, it goes against every­thing I have expe­ri­enced with using del­e­gates..

At least it is in the case of .Net 1.1”

Ahh, a lit­tle more con­text makes it that much more believ­able! But mind you, this was 2009 and .Net 3.5 had been out and sure­ly what­ev­er per­for­mance issue with del­e­gates would have been fixed long along…

The Test

So, some two years lat­er, I decid­ed to put togeth­er a quick test to see if there is any dif­fer­ence in per­for­mance between invok­ing a del­e­gate and a method in C# 4. The test is sim­ple, giv­en an emp­ty del­e­gate and method (see below), invok­ing each 10000 times in a row, which would take longer?

   1: Action MyDelegate = () => {};

   2:

   3: void MyMethod() {}

It’s worth not­ing that the test code is run in a debug, non-opti­mized (so no com­pil­er in-lin­ing) build.

The Result

Some­what sur­pris­ing­ly, invok­ing del­e­gates proved to be faster, aver­ag­ing 269 ticks over 5 runs, where as invok­ing meth­ods took an aver­age of 365 ticks!