Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the max items in a List<T>?

Tags:

c#

collections

Anybody know what the max number of items in a List is?

How do I increase that size? Or is there a collection that takes infinite items? (as much as would fit in memory, that is)

EDIT:

I get an out of memory exception when Count = 134217728 in a list of ints. got 3Gb of RAM of which 2.2 are in use. Sound normal

like image 308
Tony The Lion Avatar asked Jan 05 '10 21:01

Tony The Lion


People also ask

What is list capacity?

Capacity is the number of elements that the List<T> can store before resizing is required, whereas Count is the number of elements that are actually in the List<T>. Capacity is always greater than or equal to Count.

How much data can a list hold C#?

2147483647 because all functions off List are using int.

What is the default initial capacity of list in C#?

Following your logic "default" capacity is 1 million (after inserting a few thousands items for a good start).


1 Answers

List<T> will be limited to the max of an array, which is 2GB (even in x64). If that isn't enough, you're using the wrong type of data storage. You can save a lot of overhead by starting it the right size, though - by passing an int to the constructor.

Re your edit - with 134217728 x Int32, that is 512MB. Remember that List<T> uses a doubling algorithm; if you are drip-feeding items via Add (without allocating all the space first) it is going to try to double to 1GB (on top of the 512MB you're already holding, the rest of your app, and of course the CLR runtime and libraries). I'm assuming you're on x86, so you already have a 2GB limit per process, and it is likely that you have fragmented your "large object heap" to death while adding items.

Personally, yes, it sounds about right to start getting an out-of-memory at this point.


Edit: in .NET 4.5, arrays larger than 2GB are allowed if the <gcAllowVeryLargeObjects> switch is enabled. The limit then is 2^31 items. This might be useful for arrays of references (8 bytes each in x64), or an array of large structs.

like image 130
Marc Gravell Avatar answered Oct 05 '22 07:10

Marc Gravell