使用 BenchmarkDotNet 比较已初始化的 .NET 列表与未初始化的列表时出现 OutOfMemoryException

Sal*_*la' 2 c# benchmarkdotnet

我想创建一个基准测试来显示已初始化和未初始化的 .net 列表之间的性能差异,但我遇到了一些麻烦。我尝试了不同的方法来编写这个基准测试,但没有成功。每次运行代码时,我都会得到以下信息:

System.OutOfMemoryException: Array dimensions exceeded supported range

列表初始化基准.cs

using BenchmarkDotNet.Attributes;

namespace list_benchmark
{
    public class ListInitializationBenchmark
    {
        private List<int> notInitializedList; // Not initialized list
        private List<int> initializedList; // Initialized list with capacity

        [Params(1000, 10000, 100000)]
        public int BatchSize { get; set; }

        [GlobalSetup]
        public void GlobalSetup()
        {
            notInitializedList = new List<int>(); // Not initialized list
            initializedList = new List<int>(BatchSize); // Initialized list with capacity
        }

        [Benchmark]
        public void ProcessNotInitializedList()
        {
            for (int i = 0; i < BatchSize; i++)
            {
                notInitializedList.Add(i);
            }
        }

        [Benchmark]
        public void ProcessInitializedList()
        {
            for (int i = 0; i < BatchSize; i++)
            {
                initializedList.Add(i);
            }
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

关于如何解决这个问题有什么想法吗?

Dav*_*idG 5

BenchmarkDotNet将运行您的代码数千次,以很好地指示需要多长时间。但是,您的代码每次执行都使用相同的列表实例,这意味着它将很快耗尽空间。您需要将列表及其初始化保留在各个测试中,或者更改您的设置以在每次迭代中执行。例如:

[Benchmark]
public void ProcessNotInitializedList()
{
    List<int> notInitializedList = new List<int>();

    for (int i = 0; i < BatchSize; i++)
    {
        notInitializedList.Add(i);
    }
}

[Benchmark]
public void ProcessInitializedList()
{
    List<int> initializedList = new List<int>(BatchSize);

    for (int i = 0; i < BatchSize; i++)
    {
        initializedList.Add(i);
    }
}
Run Code Online (Sandbox Code Playgroud)

或这个:

[IterationSetup] // Iteration, not global setup
public void GlobalSetup()
{
    notInitializedList = new List<int>(); // Not initialized list
    initializedList = new List<int>(BatchSize); // Initialized list with capacity
}
Run Code Online (Sandbox Code Playgroud)