开发者

How large per list item does List<uint> get in .NET 4.0?

开发者 https://www.devze.com 2023-04-04 00:52 出处:网络
I know that it takes 4 bytes to store a uint in memory, but how 开发者_如何学Gomuch space in memory does it take to store List<uint> for, say, x number of uints?

I know that it takes 4 bytes to store a uint in memory, but how 开发者_如何学Gomuch space in memory does it take to store List<uint> for, say, x number of uints?

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


There is no per-item overhead of a List<T> because it uses a T[] to store its data. However, a List<T> containing N items may have 2N elements in its T[]. Also, the List data structure itself has probably 32 or more bytes of overhead.


You probably will notice not so much difference between T[] and list<T> but you can use

System.GC.GetTotalMemory(true);

before and after an object allocation to obtain an approximate memory usage.


List<> uses an array internally, so a List<uint> should take O(4bytes * n) space, just like a uint[]. There may be some more constant overhead in comparison to a array, but you should normally not care about this.

Depending on the specific implementation (this may be different when using Mono as a runtime instead of the MS .NET runtime), the internal array will be bigger than the number of actual items in the list. E.g.: a list of 5 elements has an internal array that can store 10, a list of 10000 elements may have an internal array of size 11000. So you cant generally say that the internal array will always be twice as big, or 5% bigger than the number of list element, it may also depend on the size.

Edit: I've just seen, Hans Passant has described the growing behaviour of List<T> here.

So, if you have a collection of items that you want to append to, and you cant know the size of this collection at the time the list is created, use a List<T>. It is specifically designed for this case. It provides fast random access O(1) to the elements, and has very little memory overhead (internal array). It is on the other hand very slow on removing or inserting in the middle of the list. If you need those operations often, use a LinkedList<T>, which has then more memory overhead (per item!), however. If you know the size of you collection from the beginning, and you know that is wont change (or just very few times) use arrays.

0

精彩评论

暂无评论...
验证码 换一张
取 消