gpt4 book ai didi

c# - .Net Dictionary 在大约 6,000,000 个条目处出现内存不足异常

转载 作者:可可西里 更新时间:2023-11-01 03:14:07 26 4
gpt4 key购买 nike

我正在使用 Dictionary<Int,Int>存储图像中颜色出现的频率,其中键是颜色(作为 int),值是颜色在图像中出现的次数。

当我处理更大/更彩色的图像时,这本词典会变得非常大。我在大约 6,000,000 个条目时遇到内存不足异常。这是在 32 位模式下运行时的预期容量吗?如果是这样,我能做些什么吗?有哪些替代方法可以跟踪这些不会耗尽内存的数据?

作为引用,下面是循环遍历位图中的像素并将频率保存在 Dictionary<int,int> 中的代码:

Bitmap b; // = something...
Dictionary<int, int> count = new Dictionary<int, int>();
System.Drawing.Color color;

for (int i = 0; i < b.Width; i++)
{
for (int j = 0; j < b.Height; j++)
{
color = b.GetPixel(i, j);
int colorString = color.ToArgb();
if (!count.Keys.Contains(color.ToArgb()))
{
count.Add(colorString, 0);
}
count[colorString] = count[colorString] + 1;
}
}

编辑:如果您想知道什么图像中有这么多不同的颜色:http://allrgb.com/images/mandelbrot.png

编辑:我还应该提到,这是在使用 .Net 4.0 的 asp.net Web 应用程序中运行的。所以可能会有额外的内存限制。

编辑:我只是在控制台应用程序中运行了相同的代码,没有遇到任何问题。该问题仅发生在 ASP.Net 中。

最佳答案

更新:鉴于 OP 的示例图像,最大项目数似乎超过 1600 万,并且 apparently即使在实例化字典时分配太多。我在这里看到三个选项:

  • 将图像缩小到可管理的大小并以此为基础进行处理。
  • 尝试转换为颜色可能性较少的配色方案。
  • 按照其他人的建议,使用固定大小的数组。

上一个答案: 问题是您没有为字典分配足够的空间。在某些时候,当它扩展时,您只是用完了扩展的内存,但不一定用于新词典。

示例:这段代码在接近 2400 万个条目时内存不足(在我的机器上,以 32 位模式运行):

Dictionary<int, int> count = new Dictionary<int, int>();
for (int i = 0; ; i++)
count.Add(i, i);

因为在上次扩展中,它当前正在为已经存在的条目使用空间,并试图为另外数百万的条目分配空间,这太多了。

现在,如果我们最初为 4000 万个条目分配空间,它运行时没有问题:

Dictionary<int, int> count = new Dictionary<int, int>(40000000);

因此尝试在创建字典时指出将有多少个条目。

来自 MSDN :

The capacity of a Dictionary is the number of elements that can be added to the Dictionary before resizing is necessary. As elements are added to a Dictionary, the capacity is automatically increased as required by reallocating the internal array. If the size of the collection can be estimated, specifying the initial capacity eliminates the need to perform a number of resizing operations while adding elements to the Dictionary.

关于c# - .Net Dictionary<int,int> 在大约 6,000,000 个条目处出现内存不足异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20643222/

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