I'm trying to understand how a C# .NET 4.0 List<T>(initSize)
allocates memory.
My problem is that I have a List<foo>
where class foo
needs at least 20 bytes of memory. I have two cases where I'll end up having either X
or X+60
elements of foo
. I don't know at allocation time which of the two cases it will be.
Since X
is greater than 36,000 elements, I'm trying to minimize unnecessary memory allocations, and I don't want to allocate twice for one List
if I can avoid it. My understanding is the size of the allocation (36k elements * 4B reference ~= 144kB) pushes the allocation on the large heap. Adding to my woes is that I have a Dictionary<key, List<foo>>
with roughly 4,000 elements.
My questions:
Does the C# run-time allocate an amount beyond the initial, specified capacity? For example, if I initialize to 36,000 entries, do I really have 65,536 entries allocated since that's the next power of 2 greater than 36,000?
Should I just allocate to
X+60
in all cases instead ofX
to avoid a 2nd allocation? 60 happens to be a constant value in this case that won't vary.
My question is similar, but different from the following:
Memory allocation for collections in .NET - because they do not initialize the List<T>
in this question.
Initial capacity of collection types, e.g. Dictionary, List - is an implementation issue in specifying initial capacity.
How to initialize a List<T> to a given size (as opposed to capacity)? - appears to be wrestling with Array
vs List<T>
, which is not my issue.