How fast does a C# method run, and is it faster than a different implementation? If we have a solid knowledge of how fast code executes, we can develop more efficient programs.
With benchmarking, we can make smarter decisions. Most of the programs we use every day have been benchmarked many times. However, incorrect benchmarks have a negative value.
In the current benchmark program, we use if
-directives as this eliminates the problem where the order of tests running affects performance.
#define VERSION1 using System; using System.Diagnostics; // Other class. class Program { public static void Main() { const int _max = 10000000; var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { #if VERSION1 // Code. #endif #if VERSION2 // Code. #endif } s1.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } }??? ns Version 1 description ??? ns Version 2 description
It is probably better to only run one test per program execution. In previous benchmarking programs, it is common to find that the second loop runs faster than the first.
The Dictionary
collection in the base class library is a huge optimization. But developers sometimes write code that results in twice as many lookups.
Benchmarking encourages careful thinking about your code. It saves nanoseconds from your software. It also improves the depth of your understanding.