List每个列表项有多大进入.NET 4.0?
我知道在内存中存储 uint
需要 4 个字节,但是存储 List
需要多少内存空间,例如 x 个 uint
数?
这与 uint[]
所需的空间相比如何?
I know that it takes 4 bytes to store a uint
in memory, but how much space in memory does it take to store List<uint>
for, say, x number of uint
s?
How does this compare to the space required by uint[]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
List
没有每项开销,因为它使用T[]
来存储其数据。但是,包含 N 个项目的List
在其T[]
中可能有 2N 个元素。此外,List
数据结构本身可能有 32 或更多字节的开销。There is no per-item overhead of a
List<T>
because it uses aT[]
to store its data. However, aList<T>
containing N items may have 2N elements in itsT[]
. Also, theList
data structure itself has probably 32 or more bytes of overhead.您可能会注意到
T[]
和list
之间没有太大区别,但您可以在对象分配之前和之后使用来获取大致的内存使用情况。
You probably will notice not so much difference between
T[]
andlist<T>
but you can usebefore and after an object allocation to obtain an approximate memory usage.
List<>
在内部使用数组,因此List
应占用 O(4bytes * n) 空间,就像uint[]
一样代码>.与数组相比,可能会有一些更恒定的开销,但您通常不应该关心这一点。根据具体的实现(当使用 Mono 作为运行时而不是 MS .NET 运行时时,这个可能会有所不同),内部数组将大于列表中实际项目的数量。例如:一个包含 5 个元素的列表有一个可以存储 10 个元素的内部数组,一个包含 10000 个元素的列表可能有一个大小为 11000 的内部数组。所以你不能笼统地说内部数组总是两倍大,或者大 5%除了列表元素的数量之外,它还可能取决于大小。
编辑:我刚刚看到,Hans Passant 描述了
List
在这里。因此,如果您有一个要附加到的项目集合,并且在创建列表时无法知道该集合的大小,请使用
List
。它是专门针对这种情况而设计的。它提供对元素的快速随机访问 O(1),并且内存开销非常小(内部数组)。另一方面,在列表中间删除或插入的速度非常慢。如果您经常需要这些操作,请使用LinkedList
,但是,它会产生更多的内存开销(每个项目!)。如果您从一开始就知道集合的大小,并且知道它不会改变(或只是很少改变),请使用数组。List<>
uses an array internally, so aList<uint>
should take O(4bytes * n) space, just like auint[]
. 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 aLinkedList<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.