Benchmarking in C#
Have you ever seen those posts people put where they have done some kind of performance tests, or benchmarking, against a couple of methods - ususally doing the same thing but in different ways?
The ones that look like this
These are actually pretty easy to do and useful if you need to analyse and tune performance critical code
You need to create a class that exposes the 2 methods you want to benchmark something like this
You need to make sure the methods use some input value. This would normally be passed in as arguments but for this we need to make sure a runtime value is provided.
You then declare your methods with [BenchMark] which comes from this nuget package
And then you just run the code in release code without debugging.
It will take a while as it performs many iterations then you will get the results.
The results in this case show that Linq is more readable but slower. So which you choose depends on performance considerations.
You can also use [Params] as below to provide more varied input.