How to validate all benchmarked methods return the same value with BenchmarkDotNet

Instead of calling your benchmark methods outside the context of BenchmarkDotNet to validate they all return the same value, let BenchmarkDotNet do that for you.

This is possible by applying the ReturnValueValidator attribute on our benchmark class like below ⬇ …

If I’m running the below ⬇ benchmarks where the StringPlus method has an ‘accidental’ ! included at the end …

BenchmarkDotNet will fail to validate the benchmarks and will show an error similar to below ⬇

This is a super useful attribute to quickly confirm we are indeed comparing apples to apples. I use it on all my benchmarks since learning about it.

Leave a Reply

Your email address will not be published. Required fields are marked *