High memory consumption with Enumerable.Range?

前端 未结 4 634
轻奢々
轻奢々 2020-11-28 16:03

Originally i wanted to know whether ToList allocates more memory than using the constructor of List which takes an IEnumerable

4条回答
  •  执念已碎
    2020-11-28 16:30

    List is implemented as an array. When you exceed what it has allocated, it allocates another array double the size (essentially doubling the memory allocation). The default capacity is 4, and it doubles things from here on.

    Most likely if you drop the number of items to say 7,500, you'll see the array drop to a little under 32 MBs, and the IList size to be 32 MBs.

    You can tell IList what the initial size should be, which is why if you give it the IEnumerable at construction time, it shouldn't over allocate memory.

    [Edit] after comments

    In the case of Enumerable.Range(a, b) it returns an IEnumerable only rather than an ICollection. For List to not overallocate the item passed during construction must also be an ICollection

提交回复
热议问题