Unlocking the Secrets of .NET Loops: Boost Performance Like a Pro

Today We will discuss Unlocking the Secrets of .NET Loops: Boost Performance Like a Pro. Until the end of this article, you will have an understanding of loops and discover some new ways to loops, also we have provided you a performance analysis of the loops.

Unlocking the Secrets of .NET Loops: Boost Performance Like a Pro

Loops are a controlled structure used for the repetitive execution of a code block. It is an essential part of a programming language because it allows the programmer to perform repetitive tasks until a condition is not met. Also, through the loop, we can iterate over a dataset or a list without writing multiple lines.

There is a set of methods through which we can achieve the functionality of .NET Loops.

  1. For Loop
  2. While Loop
  3. Do-While Loop
  4. Foreach Loop
  5. Span Foreach Loop
  6. Linq ForEach Loop

These are some of the popular loops that are used for performing iteration over the dataset or collection.

For Loop 

It is one of the most popular and used loops in all the programming languages. It takes 3 parameters (start, condition, and increment/decrement). For loops are generally used when we want to perform repetitive tasks or perform iteration over a list. It is mostly used when we want to access an indexed collection or frequently used position in a collection.

While Loop

A While Loop is one of the basic and popular loops in programming languages. It takes a single parameter (condition) and works until the condition is true. This loop is slower in comparison to the for loop because of its precomputation counter and additional checks. It is ideally good for those cases when we don’t know about the start such as reading a file till the end of the file.

Do-While Loop

Do-While loop is quite similar to the While, but the difference is this condition is checked after completing the code block also known as the Post-Condition Checked Loop. This loop is a good case for those situations when we want our code to execute at least once.

For instance, if we are creating an application for ATM (Withdraw or Deposit) money, first, you will ask for the input(withdraw or deposit) and then a code block will be executed for performing the particular operation but at the end of the operation you will ask for do you want to perform another operation if user input YES then you will return it to the initial state i.e Withdraw or Deposit this will be executed until users enter NO.

Foreach Loop

Foreach is a good case when we want to iterate over a list and direct access to the item in the collection with access to the value through position again. It is recommended in those situations when readability is more essential than iterating assume we want to sum all the numbers in a list for this case it can be a good choice but, if we want to calculate the length of a collection or list it might be not a good choice we don’t require the readability to the item.

Span Foreach Loop

Span Foreach Loop is optimized for a better performance for iterating a list. It is stack-only allocation reducing its chances of getting heap issues and gains a better grab for garbage collection. It is the best choice for memory-sensitive application which requires slicing of the array or memory buffers. When we talk about loop performance analysis which is quite good in comparison with the other loops.

Linq ForEach Loop

Linq ForEach Loop is slower than foreach and for loop because it has to take a lambda expression and transform the result into a new list making this loop very time-consuming and impactful for the code loop performance. Besides time consumption, it can be a good choice when readability over loop performance.

using System;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.InteropServices;

public class LoopBenchmarks
{
    private int[] data;

    [GlobalSetup]
    public void Setup()
    {
        data = Enumerable.Range(0, 100000).ToArray();
    }

    [Benchmark(Baseline = true)]
    public int ForLoop()
    {
        int sum = 0;
        for (int i = 0; i < data.Length; i++)
        {
            sum += data[i];
        }
        return sum;
    }

    [Benchmark]
    public int WhileLoop()
    {
        int sum = 0;
        int i = 0;
        while (i < data.Length)
        {
            sum += data[i];
            i++;
        }
        return sum;
    }

    [Benchmark]
    public int DoWhileLoop()
    {
        int sum = 0;
        int i = 0;
        do
        {
            sum += data[i];
            i++;
        } while (i < data.Length);
        return sum;
    }

    [Benchmark]
    public int ForeachLoop()
    {
        int sum = 0;
        foreach (var item in data)
        {
            sum += item;
        }
        return sum;
    }

    [Benchmark]
    public int SpanForeachLoop()
    {
        int sum = 0;
        Span spanData = data;
        foreach (var item in spanData)
        {
            sum += item;
        }
        return sum;
    }

    [Benchmark]
    public int LinqForEach()
    {
        int sum = 0;
        data.ToList().ForEach(item => sum += item);
        return sum;
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BenchmarkRunner.Run();
    }
}

Here is a short brief about the performance review of loops.

Performance Analysis of Loops

To learn more about loops and performance analysis in .NET 8 Click Here. You can also read more about 5 Underestimated LINQ Methods In .Net 8.

Leave a Comment