gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:54:50 25 4
gpt4 key购买 nike

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

System.OutOfMemoryException:数组维度超出支持范围

ListInitializationBenchmark.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);
}
}
}
}

知道如何解决这个问题吗?

最佳答案

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);
}
}

或者这个:

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

关于c# - 使用 BenchmarkDotNet 比较已初始化的 .NET 列表与未初始化的列表时出现 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76300520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com