.NET 9 Loop optimizations, is it more than remove the zero extension?

60 views Asked by At

So, upon reading new updates in .NET 9, I got attracted to this section about Loop optimizations: https://learn.microsoft.com/en-us/dotnet/core/whats-new/dotnet-9/overview#loop-optimizations

As I understand, here's what they explained, consider this snippet of code

static int Sum(int[] arr)
{
    int sum = 0;
    for (int i = 0; i < arr.Length; i++)
    {
        sum += arr[i];
    }

    return sum;
}

The variable i is 4 bytes as it is an integer. The act of using it as an accessor for the array like arr[i] would required to extend i to 8 bytes. This process is called "zero-extend". For those who don't know, Zero-extend means extend the variable i from 4 bytes to 8 bytes by appending zeroes to "extended" bits. And .NET 9 improve the loop by removing the process of zero extension.

As the example quite simple, I'm curious would this improvement can affect in more complex cases? Like if I using for loop to populate and append object into a list, would it be beneficial?

List<ClassA> list = new List<ClassA>();
for (int i = 0; i < 10; i++)
{
    ClassA data = db.FirstOrDefault(x => x.Id == i);
    data.doSomething();
    list.Add(data)
}
0

There are 0 answers