可枚举范围和内存分配 [英] Enumerable.Range and Memory allocation
问题描述
我有以下代码:
IEnumerable<int> elements = Enumerable.Range(1, Int32.MaxValue);
Console.WriteLine("Size of System.Int32: {0}", sizeof(int));
Console.Write("Iterating over {0} elements... ", elements.Count());
Parallel.ForEach(elements, _ => { });
Console.WriteLine("Done.");
打印输出:
> Size of System.Int32: 4
> Iterating over 2147483647 elements... Done.
但是,我不明白为什么它没有抛出OutOfMemoryException
.
However, I don't understand why is this not throwing an OutOfMemoryException
.
知道每个int
值占用4
个字节的空间,分配Int32.MaxValue
个int
的量应该占用〜8GB
Knowing that each int
value takes up 4
bytes of space, allocating Int32.MaxValue
amount of int
should take up ~ 8GB
检查我的应用程序,该过程占用了大约aprox. 〜5.200KB.
Inspecting my application, the process is taking up aprox. ~ 5.200KB.
元素正在成功迭代,因此必须将它们分配到某个地方,对吧?
The elements are being iterated successfully so they must be allocated somewhere, right?
LINQ如何实现这一目标?
How does LINQ achieve this?
推荐答案
IEnumerable<int>
不是数组.它本身不存储任何信息.实现它的类能够循环一组值.
IEnumerable<int>
is not an array. It doesn't store any information itself. The class implementing it is capable of looping over a set of values.
此处的值未存储在数组中,而是仅进行迭代并产生每次迭代的结果.
The values here are not stored in an array, instead of that is just iterates and yields the result of every iteration.
类似这样的东西:
public IEnumerable<int> GetRange(int start, int number)
{
for (int i = start; i < start + number; i++)
{
yield return i;
}
}
请参阅,没有数组,没有存储.它只记住迭代器中的当前位置,并且可以执行适当的步骤来获取下一个位置.这段代码是由C#编译器即时生成的.
See, no arrays, no storage. It just remembers the current position in the iterator and can execute the appropriate steps to get the next one. This code is generated by the C# compiler on the fly.
这篇关于可枚举范围和内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!