Profile picture Schedule a Meeting
c a n d l a n d . n e t

Race between the If statement and the Delegate Swapping/Substitution Pattern

Dusty Candland | |

Which is faster delegate swapping or simple if statements? I wanted to know too and it turns out it’s a tie, as far as I can see. The idea is that you might have some code you want to  execute until some condition occurs then execute some different code. This might be a run once thing or a run until X is true. Either way you could use an if statement. However, many times I prefer to use a delegate, I think it looks better and the code is easier to read. Anyway, I created a small program to test this and here are the results:races

10000:10000 calls using Delegates averaging 0.005937576 seconds. 10000:10000 calls using Ifs       averaging 0.005312568 seconds. 5000:10000 calls using Delegates averaging 0.005156316 seconds. 5000:10000 calls using Ifs       averaging 0.005156316 seconds. 2:10000 calls using Delegates averaging 0.005000064 seconds. 2:10000 calls using Ifs       averaging 0.005156316 seconds. 1:10000 calls using Delegates averaging 0.005000064 seconds. 1:10000 calls using Ifs       averaging 0.005156316 seconds.

I declare a tie because different runs of the program yield slightly different results even though the run times are averaged over 100 runs. The first number is the number of times the TaskOne method is called, the second number is the total number of times the run method was called. Each set was run 100 times for the averaging seconds number.

Pseudo code for the Ifs method:

public void Ifs()
{
if (!TaskOneIsComplete())
TaskOne();
TaskTwo();
}

Pseudo code for the Delegates method:

public void Delegates()
{
_executeMe();
}

private void InitialDelegate()
{
TaskOne();
TaskTwo();

if (TaskOneIsComplete())
_executeMe = AfterDelegate;
}

private void AfterDelegate()
{
TaskTwo();
}

DelegateSubstitutionVSIfStatements.cs (2.96 KB)

Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: