How does a large list item contain a <uint> list in .NET 4.0?

I know that it takes 4 bytes to store a uint in memory, but how much memory does it take to store a List<uint> for, say, x the number of uint s?

How does this relate to the space required by uint[] ?

+4
source share
3 answers

There is no List<T> overhead because T[] is used to store data. However, a List<T> containing N elements may contain 2N elements in T[] . In addition, the List data structure itself has probably 32 or more overhead bytes.

+3
source

You probably won't notice so much the difference between T[] and list<T> , but you can use

 System.GC.GetTotalMemory(true); 

before and after allocating an object to get approximate memory usage.

+1
source

List<> uses an array inside, so a List<uint> should occupy O (4bytes * n), like uint[] . There may be some additional overhead compared to an array, but you usually don't need to do this.

Depending on the particular implementation (this may be different when using Mono as the runtime instead of the MS.NET runtime), the internal array will be larger than the number of actual elements in the list. For example: a list of 5 elements has an internal array that can store 10, a list of 10,000 elements can have an internal array of size 11,000. Thus, you cannot say that the internal array will always be twice as large or 5% larger than the number list items, it may also depend on size.

Edit: I just saw Hans Passant described the growing List<T> behavior here .

So, if you have a collection of elements that you want to add, and you cannot know the size of this collection at the time of creating the list, use List<T> . It is specially designed for this occasion. It provides O (1) fast random access to elements and has very few memory resources (internal array). On the other hand, it is very slow when deleting or pasting in the middle of a list. If you need these operations often, use LinkedList<T> , which then has more memory overhead (per element!). If you know the size of your collection from the start, and you know that this will not change (or just a few times), use arrays.

0
source

All Articles