I learnt a neat trick for comparing changes when performance profiling

 

At the moment I am working on a C# application where we are focused on improving the performance. Nothing very exciting so far.

One of the issues with performance profiling and optimisation is how do you prove that a change that you make has improved the performance as it can also be dependent on external factors?

I am currently using a very simple pattern to try and negate this as much as possible – it won’t totally eliminate it but it will have a good go! It assumes that there are a “decent” number of calls to the code being changed.

The easiest way to explain it is probably an example.

We have a method, “OriginalMethod”, which we want to improve. So we make a copy of it, “OriginalMethodCopy”, and create our new and hopefully improved version, “SuperFastMethod”.

We then create a static boolean called “_flip” and use this to choose which version to run.

 

private static bool _flip;

public void OriginalMethod()

{

_flip = !_flip;

if (_flip)

    OriginalMethodCopy();

else

    SuperFastMethod();

}

 

Now we can look in the profiler and half the calls will have gone to the new one and half to the old one and we can determine if our change worked.