runtime: for loop performance regression

Description

I found a performance regression through benchmark testing of the Loop Optimizations: IV Widening sample.

// * Summary *

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22631.3737/23H2/2023Update/SunValley3) 12th Gen Intel Core i5-12500, 1 CPU, 12 logical and 6 physical cores .NET SDK 9.0.100-preview.6.24328.19 [Host] : .NET 9.0.0 (9.0.24.32707), X64 RyuJIT AVX2 Job-SMYUOB : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2 Job-VNQOKB : .NET 9.0.0 (9.0.24.32707), X64 RyuJIT AVX2

OutlierMode=DontRemove MemoryRandomization=True

Method Runtime Count Mean Error StdDev
LoopOptimizations .NET 8.0 100 35.57 ns 0.159 ns 0.149 ns
LoopOptimizations .NET 9.0 100 37.21 ns 0.379 ns 0.354 ns
LoopOptimizations .NET 8.0 1000 283.27 ns 3.790 ns 3.545 ns
LoopOptimizations .NET 9.0 1000 306.69 ns 2.008 ns 1.878 ns
LoopOptimizations .NET 8.0 10000 2,742.63 ns 9.215 ns 8.620 ns
LoopOptimizations .NET 9.0 10000 3,013.27 ns 36.646 ns 34.278 ns

Reproduction Steps

using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Environments;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;

var config = DefaultConfig.Instance
    .AddJob(Job.Default.WithRuntime(CoreRuntime.Core80))
    .AddJob(Job.Default.WithRuntime(CoreRuntime.Core90));

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args, config);

[MemoryRandomization]
public class Benchmark
{
    private int[] _arr = null!;

    [Params(100, 1000, 10000)]
    public int Count { get; set; }

    [GlobalSetup]
    public void GlobalSetup()
    {
        _arr = new int[Count]; 
    }

    [Benchmark]
    public void LoopOptimizations()
    {
        int[] arr = _arr;

        Sum(arr);
    }

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

        return sum;
    }
}

Expected behavior

.NET 9 should be faster or at least as fast as .NET 8.

Actual behavior

.NET 9 is slower than .NET 8.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 41 (23 by maintainers)

Most upvoted comments

Let’s close this, thanks for the measurements to both of you!

BenchmarkDotNet v0.14.0, Windows 11 (10.0.22631.4037/23H2/2023Update/SunValley3) 13th Gen Intel Core i5-13600KF, 1 CPU, 20 logical and 14 physical cores .NET SDK 9.0.100-preview.7.24407.12 [Host] : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2 Job-VLHYBT : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2 Job-DOGKBI : .NET 9.0.0 (9.0.24.40507), X64 RyuJIT AVX2

OutlierMode=DontRemove MemoryRandomization=True

Method Runtime Count Mean Error StdDev
LoopOptimizations .NET 8.0 100 33.51 ns 0.674 ns 0.749 ns
LoopOptimizations .NET 9.0 100 28.61 ns 0.056 ns 0.053 ns
LoopOptimizations .NET 8.0 1000 254.07 ns 0.431 ns 0.403 ns
LoopOptimizations .NET 9.0 1000 209.06 ns 1.124 ns 1.051 ns
LoopOptimizations .NET 8.0 10000 2,531.61 ns 42.090 ns 39.371 ns
LoopOptimizations .NET 9.0 10000 2,014.09 ns 13.000 ns 12.161 ns

It seems that Preview 7 has achieved better performance. @jakobbotsch

@EgorBot -intel -profiler -commit 813d743a72f731781ce68233f1082d83d8090f88 vs previous

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BenchmarkDotNet.Attributes;

public class Benchmark
{
    private List<int> _list = new List<int>(Enumerable.Range(0, 512));

    [Benchmark]
    public List<int> ListIndexerSet()
    {
        var list = _list;
        for (int i = 0; i < list.Count; i++)
            list[i] = default;
        return list;
    }
}

@EgorBot -intel -commit 813d743a72f731781ce68233f1082d83d8090f88 vs previous --disasm --envvars “DOTNET_JitDisasm:ListIndexerSet”

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BenchmarkDotNet.Attributes;

public class Benchmark
{
    private List<int> _list = new List<int>(Enumerable.Range(0, 512));

    [Benchmark]
    public List<int> ListIndexerSet()
    {
        var list = _list;
        for (int i = 0; i < list.Count; i++)
            list[i] = default;
        return list;
    }
}

@EgorBot -intel 813d743a72f731781ce68233f1082d83d8090f88 vs ea77071233162673558cbe8156649dfaf8f74ca7 --disasm

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BenchmarkDotNet.Attributes;

public class Benchmark
{
    private List<int> _list = new List<int>(Enumerable.Range(0, 512));

    [Benchmark]
    public List<int> ListIndexerSet()
    {
        var list = _list;
        for (int i = 0; i < list.Count; i++)
            list[i] = default;
        return list;
    }
}

@EgorBot -intel 813d743a72f731781ce68233f1082d83d8090f88 vs previous --disasm

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using BenchmarkDotNet.Attributes;

public class Benchmark
{
    private List<int> _list = new List<int>(Enumerable.Range(0, 512));

    [Benchmark]
    public List<int> ListIndexerSet()
    {
        var list = _list;
        for (int i = 0; i < list.Count; i++)
            list[i] = default;
        return list;
    }
}

Thanks a lot for those results. I will try to take a look at them soon, however, I think the original loop perf should be fixed in preview 7 by virtue of strength reduction. Feel free to try that out once preview 7 is available.

@SystematicChaos012 Thanks a lot for helping to investigate this.

I’m curious, does the difference reproduce for you with a simple standalone app? Make sure to set the environment variable DOTNET_TieredCompilation=0 before running this.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

class Program
{
    static void Main(string[] args)
    {
        int[] arr = new int[10000];
        Stopwatch timer = new Stopwatch();

        for (int i = 0; i < 10; i++)
        {
            timer.Restart();
            for (int j = 0; j < 100000; j++)
            {
                Sum_nint_unsafe_unwidened_widened(arr);
            }
            Console.WriteLine("Sum_nint_unsafe_unwidened_widened: {0:F2} us per invoc", timer.Elapsed.TotalMilliseconds * 1000 / 100000);
        }

        for (int i = 0; i < 10; i++)
        {
            timer.Restart();
            for (int j = 0; j < 100000; j++)
            {
                Sum_int(arr);
            }
            Console.WriteLine("Sum_int: {0:F2} us per invoc", timer.Elapsed.TotalMilliseconds * 1000 / 100000);
        }
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Sum_int(int[] arr)
    {
        int sum = 0;
        for (int i = 0; i < arr.Length; i++)
        {
            sum += arr[i];
        }

        return sum;
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }
}

If it does and you wouldn’t mind then it would be very helpful if you can compare the VTune microarchitectural profile traces of the different versions. The difference in those two traces should help us definitively try to figure out whether the CPU is benefitting from something due to the widening, or whether there are any other effects (like, say, just the code size differences).

@EgorBot -arm64 -commit 42b2b19e883f06af5771b5d85b26af263c62e781 vs c09ec6552f11b74a2e825cb63cb7c45f5552d3f2 --disasm

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public class Benchmark
{
    private int[] _arr = null!;

    [Params(10000)]
    public int Count { get; set; }

    [GlobalSetup]
    public void GlobalSetup()
    {
        _arr = new int[Count];
    }

    [Benchmark(Baseline = true)]
    public void LoopOptimizations_int()
    {
        int[] arr = _arr;

        Sum_int(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint()
    {
        int[] arr = _arr;

        Sum_nint(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe()
    {
        int[] arr = _arr;

        Sum_nint_unsafe(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_widened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_widened(arr);
    }

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

        return sum;
    }

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

        return sum;
    }

    private static int Sum_nint_unsafe(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }
}

@EgorBot -intel -amd -commit 42b2b19e883f06af5771b5d85b26af263c62e781 vs c09ec6552f11b74a2e825cb63cb7c45f5552d3f2 --disasm

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public class Benchmark
{
    private int[] _arr = null!;

    [Params(10000)]
    public int Count { get; set; }

    [GlobalSetup]
    public void GlobalSetup()
    {
        _arr = new int[Count];
    }

    [Benchmark(Baseline = true)]
    public void LoopOptimizations_int()
    {
        int[] arr = _arr;

        Sum_int(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint()
    {
        int[] arr = _arr;

        Sum_nint(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe()
    {
        int[] arr = _arr;

        Sum_nint_unsafe(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_widened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_widened(arr);
    }

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

        return sum;
    }

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

        return sum;
    }

    private static int Sum_nint_unsafe(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }
}

@EgorBot -arm64 -intel -amd -commit 42b2b19e883f06af5771b5d85b26af263c62e781 vs c09ec6552f11b74a2e825cb63cb7c45f5552d3f2 --disasm

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public class Benchmark
{
    private int[] _arr = null!;

    [Params(10000)]
    public int Count { get; set; }

    [GlobalSetup]
    public void GlobalSetup()
    {
        _arr = new int[Count];
    }

    [Benchmark(Baseline = true)]
    public void LoopOptimizations_int()
    {
        int[] arr = _arr;

        Sum_int(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint()
    {
        int[] arr = _arr;

        Sum_nint(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe()
    {
        int[] arr = _arr;

        Sum_nint_unsafe(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_widened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_widened(arr);
    }

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

        return sum;
    }

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

        return sum;
    }

    private static int Sum_nint_unsafe(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }
}

@EgorBot -arm64 -intel -amd -commit 42b2b19e883f06af5771b5d85b26af263c62e781 --disasm

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args);

public class Benchmark
{
    private int[] _arr = null!;

    [Params(10000)]
    public int Count { get; set; }

    [GlobalSetup]
    public void GlobalSetup()
    {
        _arr = new int[Count];
    }

    [Benchmark(Baseline = true)]
    public void LoopOptimizations_int()
    {
        int[] arr = _arr;

        Sum_int(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint()
    {
        int[] arr = _arr;

        Sum_nint(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe()
    {
        int[] arr = _arr;

        Sum_nint_unsafe(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_unwidened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_unwidened(arr);
    }

    [Benchmark]
    public void LoopOptimizations_nint_unsafe_unwidened_widened()
    {
        int[] arr = _arr;

        Sum_nint_unsafe_unwidened_widened(arr);
    }

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

        return sum;
    }

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

        return sum;
    }

    private static int Sum_nint_unsafe(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; i < arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_unwidened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i = (nint)((nuint)((uint)i + 1)))
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }

    private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
    {
        int sum = 0;
        for (nint i = 0; (uint)i < (uint)arr.Length; i++)
        {
            sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
        }

        return sum;
    }
}

Thanks for running those measurements. I still am unable to reproduce the results, even on my own Intel CPU:

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22635.3858) Intel Core i9-10885H CPU 2.40GHz, 1 CPU, 16 logical and 8 physical cores .NET SDK 9.0.100-preview.6.24328.19 [Host] : .NET 8.0.7 (8.0.724.31311), X64 RyuJIT AVX2 Job-JKDKMJ : .NET 9.0.0 (9.0.24.32707), X64 RyuJIT AVX2

Runtime=.NET 9.0

Method Count Mean Error StdDev Ratio
LoopOptimizations_int 10000 2.766 us 0.0204 us 0.0160 us 1.00
LoopOptimizations_nint 10000 2.459 us 0.0356 us 0.0333 us 0.89
LoopOptimizations_nint_unsafe 10000 2.730 us 0.0350 us 0.0327 us 0.99
LoopOptimizations_nint_unsafe_unwidened 10000 2.732 us 0.0328 us 0.0307 us 0.99
LoopOptimizations_nint_unsafe_unwidened_unwidened 10000 2.754 us 0.0187 us 0.0166 us 1.00
LoopOptimizations_nint_unsafe_unwidened_widened 10000 2.739 us 0.0105 us 0.0087 us 0.99

LoopOptimizations_nint being faster is #104665.

I still have my suspicions that there is some micro architectural artifact here… Going to see if I can run the benchmarks on some more CPUs.

Interesting – it seems your CPU really benefits from having the i++ and compare widened as well. Actually, I am not sure whether it is just the i++ or also the compare that should be widened – do you mind measuring the following variant too? This one only widens the i++. Hopefully the last one this time 😃

private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
{
    int sum = 0;
    for (nint i = 0; (uint)i < (uint)arr.Length; i++)
    {
        sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
    }

    return sum;
}

Thank you for measuring! Those are some interesting results. Here’s another couple of variants if you don’t mind:

private static int Sum_nint_unsafe_unwidened(int[] arr)
{
    int sum = 0;
    for (nint i = 0; i < arr.Length; i = (nint)((nuint)((uint)i + 1)))
    {
        sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
    }

    return sum;
}

private static int Sum_nint_unsafe_unwidened_unwidened(int[] arr)
{
    int sum = 0;
    for (nint i = 0; (uint)i < (uint)arr.Length; i = (nint)((nuint)((uint)i + 1)))
    {
        sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
    }

    return sum;
}

private static int Sum_nint_unsafe_unwidened_widened(int[] arr)
{
    int sum = 0;
    for (nint i = 0; (uint)i < (uint)arr.Length; i++)
    {
        sum += Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(arr), i);
    }

    return sum;
}

Here’s some properties of the codegen of each version:

i widened i++ widened i < arr.Length widened Bounds check Relative loop offset
int Yes No No No 0x11
nint Yes Yes Yes Yes 0x20 (aligned by JIT)
nint_unsafe Yes Yes Yes No 0xD
nint_unsafe_unwidened Yes No Yes No 0xD
nint_unsafe_unwidened_unwidened Yes No No No 0xD
nint_unsafe_unwidened_widened Yes Yes No No 0xD

I am trying to figure out whether your CPU is benefiting from the specific alignment of the loop (starting at 0xD) or whether it is benefitting from the widened i++/compare in the loop. IV widening does not widen the i++ or compare operations of the loop, so if this is what is benefitting your CPU, then we should consider having the JIT widen the operations when possible, even though this is a size increase in the codegen.

I was about to make the same comment as @huoyaoyuan. There are likely micro-architectural effects here causing the difference. E.g. on my laptop I get

BenchmarkDotNet v0.13.12, Windows 11 (10.0.22635.3858) Intel Core i9-10885H CPU 2.40GHz, 1 CPU, 16 logical and 8 physical cores .NET SDK 9.0.100-preview.6.24328.19 [Host] : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX2 Job-SQBFGS : .NET 8.0.6 (8.0.624.26715), X64 RyuJIT AVX2 Job-MCCPZY : .NET 9.0.0 (9.0.24.32707), X64 RyuJIT AVX2

Method Runtime Count Mean Error StdDev
LoopOptimizations .NET 8.0 100 35.33 ns 0.615 ns 0.821 ns
LoopOptimizations .NET 9.0 100 36.55 ns 0.590 ns 0.552 ns
LoopOptimizations .NET 8.0 1000 298.34 ns 5.909 ns 9.873 ns
LoopOptimizations .NET 9.0 1000 294.27 ns 5.840 ns 7.594 ns
LoopOptimizations .NET 8.0 10000 2,792.73 ns 45.144 ns 37.697 ns
LoopOptimizations .NET 9.0 10000 2,818.92 ns 35.169 ns 31.177 ns

But I can also see some bimodality with the benchmark:

-------------------- Histogram --------------------
[2.714 us ; 2.816 us) | @@@@@@@@@@
[2.816 us ; 2.895 us) | @@@
---------------------------------------------------

(not as large of a difference as yours, but still a ~7% difference in perf from run-to-run)

One thing I noticed looking at the disassembly is that we have additional prolog in .NET 9, which affects the loop’s relative starting offset.

Method Program:Sum(int[]):int (FullOpts)
 ; Emitting BLENDED_CODE for X64 with AVX - Windows
 ; FullOpts code
@@ -7,8 +166,9 @@
 ; No PGO data
 
 G_M000_IG01:                ;; offset=0x0000
+       sub      rsp, 40
  
-G_M000_IG02:                ;; offset=0x0000
+G_M000_IG02:                ;; offset=0x0004
        xor      eax, eax
        xor      edx, edx
        mov      r8d, dword ptr [rcx+0x08]
@@ -16,15 +176,16 @@ G_M000_IG02:                ;; offset=0x0000
        jle      SHORT G_M000_IG04
        align    [0 bytes for IG03]
  
-G_M000_IG03:                ;; offset=0x000D
+G_M000_IG03:                ;; offset=0x0011
-       mov      r10d, edx
-       add      eax, dword ptr [rcx+4*r10+0x10]
+       add      eax, dword ptr [rcx+4*rdx+0x10]
        inc      edx
        cmp      r8d, edx
        jg       SHORT G_M000_IG03
  
 G_M000_IG04:                ;; offset=0x001C
+       add      rsp, 40
        ret      
  
-; Total bytes of code 29
+; Total bytes of code 33

I opened #104658 for that.