When working with applications, you will often want to know the memory allocation, garbage collection (GC) overhead, and throughput of the code. Your application might be slow, or it might be consuming a lot of resources, and you want to find out what’s wrong.

Although you can detect functional problems and code defects using unit tests and code reviews, you might still need a way to isolate performance issues. Here’s where NBench comes in handy. This article presents a discussion of NBench and how we can use it to write performance tests for .NET applications.

What is NBench? Why should I use it?

NBench is a popular performance testing framework that can be used to profile the performance of methods in our application. NBench can measure the throughput of your application’s code, the memory allocation, and the GC overhead involved in reclaiming memory by cleaning up unwanted objects.

You can leverage NBench to “unit test” your application’s performance much the same way you write unit tests using the XUnit or NUnit frameworks. The thing I like best about NBench is that it can be integrated into your build pipeline. And even though NBench has its own runner, you can still run NBench using NUnit or Resharper. It feels just like running your unit tests.

as well. Pro.NBench.xUnit allows you to discover, run, or debug NBench tests using xUnit in ReSharper. 

Writing performance tests using NBench

Let’s explore how we can write and execute performance tests using NBench. Create a new class library project, and save it with a helpful name. Next, add the NBench and NBench.Runner packages I mentioned above. Here is the start of our NBench performance test method.

and at the .