C# Large object in medium size collection
Asked Answered
R

1

10

I'm pretty new to the memory problem. Hope you don't think this is a stupid question to ask.

I know that memory larger than 85,000 Bytes would be put into LOH in C# i.e.

Byte[] hugeByteCollection = new Byte[85000]; 

I'm wondering if a collection with size 10000 - 20000 with an object that contains 10 member variables (byte type) will be put into LOH or SOH ?

Repudiate answered 5/9, 2015 at 16:32 Comment(0)
D
4

The size of an array of objects is the number of objects times the pointer size. This is because only value types is stored in the array itself, reference types (objects) will be stored somewhere else and will not count towards the size of the array. So 85000/4=21250 objects, and 85000/8=10625 objects can be stored in an array on the SOH in 32bit and 64bit mode, respectively.

Edit: Thanks to Hans Passant for pointing out that this assumes that the collection type used is an array and not a list. Lists resize themselves to be bigger than the content to avoid too many allocations. See this link for details

Demonic answered 5/9, 2015 at 16:44 Comment(4)
That kind of math doesn't work for collection types, it is actually 16,384. Check this answer for details.Linnea
Thanks for your comment! The resizing that you talk about is only for lists, not arrays, so not directly related to this question. But still, I should have added the warningDemonic
so in order to keep the list in SOH for list that contains large number of objects We need to come up with a partitioned list that contains an array of list. The partitionList will dynamically created a new List and added to the arry when the list exceed the capacity of 10000 Will that work ?Repudiate
It will. But once your list reaches that size, the LOH is the faster option. I don't see why you would insist on keeping it in the SOH?Demonic

© 2022 - 2024 — McMap. All rights reserved.