Swacblooms🦋

Making the Moves
Menu
  • Home
  • Motivation
  • Education
  • Programming
  • About
  • Contact
  • Privacy Policy
Home
Uncategorized
Benchmarking in C#
Uncategorized

Benchmarking in C#

Samson Amaugo April 13, 2022

Hello guys, so in this article, I would be writing about how to perform Benchmarks in your C# console application.
The good thing about this implementation is that it is super easy.
A benchmark could be described as a series of test used to compare the performance of different code implementations based on a particular criterion or different criterias.

For Example I have this class below:

public class Loops
{
    private readonly int[] _values;

    public Loops()
    {
        _values = Enumerable.Range(0, 100).ToArray();
    }

    public int ForLoopWithArray()
    {
        var total = 0;
        for (var i = 0; i < _values.Length; i++) total += _values[i];
        return total;
    }

    public int ForEachLoopWithArray()
    {
        var total = 0;
        foreach (var i in _values) total += i;
        return total;
    }
}

So in the code above I want to see if the ForEachLoopWithArray method is faster than the ForLoopWithArray method.

You could possibly just add a timer before code execution and calculate the difference between time before code execution and when execution stops. But that won’t be very accurate due to it isn’t tested several time. You could then decide to create a more accurate benchmark by executing the code multiple times, finding the mean and standard deviation of all the runs and comparing it to the code execution of the relative code.

But instead of going through all these hassle. There is a really cool DotNet library called  BenchmarkDotNet 🥂🥂

You can add the BenchmarkDotNet NuGet to your project using the dotnet cli command:

dotnet add package BenchmarkDotNet 

You can check this link to see other ways of doing that.

BenchmarkDotNet allows you to easily attach an attributes (Benchmark attributes) to the methods you want to test or compare. And that is all you need to implement the magical wonders of BenchmarkDotNet.

Next, all you need to do is to call the Run method in the BenchmarkDotNet class using the name of the class containing your test methods as the its Generic Type.

The code below shows my complete code using the BenchmarkDotNet library to run the Benchmark.

// See https://aka.ms/new-console-template for more information

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

BenchmarkRunner.Run<Loops>();

public class Loops
{
    private readonly int[] _values;

    public Loops()
    {
        _values = Enumerable.Range(0, 100).ToArray();
    }

    [Benchmark]
    public int ForLoopWithArray()
    {
        var total = 0;
        for (var i = 0; i < _values.Length; i++) total += _values[i];
        return total;
    }

    [Benchmark]
    public int ForEachLoopWithArray()
    {
        var total = 0;
        foreach (var i in _values) total += i;
        return total;
    }
}

Note :- The code above uses c# 10 syntax and also ensure that you execute your code in release mode for proper execution and benchmarking

Execution of the code above would take some minutes or seconds based on the computing power of your processor.

After waiting for a while I got the result below :-

From the analysis, you could see that the ForEachLoopWithArray method performed better in speed during the series of testing

There are also other scenarios that would make a forloop to be faster than a foreach loop in c# and that is where you talk about lowering your C# code and also conversion of your C# code to IL (Intermediate Language) format to understand how the C# compiler sees your code and executes it.

I guess that would be an article for another day 🥂

Thanks for reading through 😜

Prev Article
Next Article

Related Articles

face your fear
On a day to day basis, we are fascinated by …

The Preconceptions of Talent, is it over-hyped?

Ok, we’ve gotten to the final stage and that is …

How to make a PWA and host in Azure-3

About The Author

Samson Amaugo

I am Samson Amaugo. I am a full-stack developer and I specialize in DotNet and the MERN stack.

Leave a Reply

Cancel reply

Search Site

Recent Posts

  • Running Entity Framework Migrations in an Aspire-Bootstrapped Orleans Project
  • Using XDebug in Laravel Sail (VSCODE)
  • Custom Redis Streams Provider for Orleans
  • Creating a Custom File Storage Provider for Microsoft Orleans
  • Incremental Generators In C#

Categories

  • EDUCATION
  • Motivation
  • Programming
  • Uncategorized

Get more stuff

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for subscribing.

Something went wrong.

we respect your privacy and take protecting it seriously

RSS Swacblooms

  • Running Entity Framework Migrations in an Aspire-Bootstrapped Orleans Project
  • Using XDebug in Laravel Sail (VSCODE)
  • Custom Redis Streams Provider for Orleans
  • Creating a Custom File Storage Provider for Microsoft Orleans
  • Incremental Generators In C#
  • Hot Chocolate Data Loader: A Quick Guide
  • Exploring Policy-Based Authorization in Minimal API with .NET 8
  • Using Cloud Firestore in Blazor WebAssembly
  • Serving A VueJs App from DotNet
  • Dynamic Subscriptions in Hot Chocolate 🔥🍫

Swacblooms🦋

Making the Moves
Copyright © 2025 Swacblooms🦋
Swacblooms - Making the Moves