Listing and memory allocation

I have the following code:

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.");

This produces:

> Size of System.Int32: 4
> Iterating over 2147483647 elements... Done.

However, I do not understand why this is not throwing away OutOfMemoryException.

Knowing that each value intoccupies 4space bytes, the allocation of the Int32.MaxValuesum intshould take ~ 8 GB

Checking my application, the process takes aprox. ~ 5.200KB.

Elements are successfully repeated, so they should be highlighted somewhere, right?

How does LINQ achieve this?

+4
source share
1 answer

IEnumerable<int>not an array. It does not store any information. A class that implements it is able to iterate over a set of values.

, .

- :

public IEnumerable<int> GetRange(int start, int number)
{
    for (int i = start; i < start + number; i++)
    {
        yield return i;
    }
}

, , . . # .

+12

Source: https://habr.com/ru/post/1612275/


All Articles