About
In this code snippet, we’ll see how to benchmark C# code.
Benchmarking can be useful to find out how well a certain piece of code is performing. We can look at how much time it takes to execute it and how much memory gets used in the process.
You can test out multiple approaches to solving a problem and see which one is the most optimal one. Sometimes the difference might be very small but this can become important when/if you need your code scale to handle a lot of executions/requests.
You can also run automated benchmarks as part of your CI/CD pipeline to monitor and make sure your application isn’t getting slower as a result of you adding some new code to it.
To be able to benchmark our C# we first need to install this nuget package.
Let’s see how to benchmark our code below.
Code:
using BenchmarkDotNet.Attributes; //Add BenchmarkDotNet to this file. using BenchmarkDotNet.Running; using System.Collections; Console.WriteLine("Starting..."); //Run the benchmark on the test class. BenchmarkRunner.Run<Test>(); Console.WriteLine("Finished."); Console.ReadLine(); [MemoryDiagnoser] //When the results will be shown the memory usage will be also included. [Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)] //When the results will be shown they will be ordered from fastest to slowest. public class Test { //When the benchmark is run on the Test class all the methods that have the [Benchmark] attribute will get benchmarked. [Benchmark] public void ArrayTest() { Random rnd = new Random(10654); int[] myArray = new int[1000000]; for (int i = 0; i < myArray.Length; i++) { myArray[i] = rnd.Next(); } for (int i = 0; i < myArray.Length; i++) { myArray[i] += 50; } } [Benchmark] public void ArrayListTest() { Random rnd = new Random(10654); ArrayList myArray = new ArrayList(); for (int i = 0; i < 1000000; i++) { myArray.Add(rnd.Next()); } for (int i = 0; i < myArray.Count; i++) { myArray[i] = (int)myArray[i] + 50; } } [Benchmark] public void ListTest() { Random rnd = new Random(10654); List<int> myArray = new List<int>(); for (int i = 0; i < 1000000; i++) { myArray.Add(rnd.Next()); } for (int i = 0; i < myArray.Count; i++) { myArray[i] = myArray[i] + 50; } } }