Search code examples
.netheap-memoryclr

.NET CLR: How does runtime calculate size of object?


There is Large Object Heap in .NET for objects with size more than 85kb. As I understand size of object in heap calculated like this

  1. size of all properties and fields of primitive types and instances of value types (because they are stored inside parent instance)
  2. size of references to other instances of classes (because they are stored separately).

Examples:

  1. 10 objects of reference type (each 10kb) and one object of reference type which contains all of them => all objects should not be put into LOH
  2. 2 objects of reference type (each 86kb) and object of reference type which contains all of them => 2 objects in LOH but last one in usual heap

Is it correct calculation schema? Are my examples correct?


Solution

  • The allocation cost of a reference type in the CLR is comprised of a fixed overhead (dependent on architecture) plus the total amount of its members (all are eventually values, even references, 4-byte or 8-byte).

    Refer to: What is the memory overhead of a .NET Object

    It does not allocate the memory space of a referred object, just the reference value.

    If you allocate a 10KB object, it won't hit the LOH.

    If you allocate an array of 10 x 10KB classes, neither the list nor the objects will be in the LOH. The list will in fact be an array of 10 x size of reference for architecture.

    If your class was a struct, the list would include the memory space required to house the 10KB struct, 10 times, which in theory would plonk the list (and by virtue of value-types, the objects too) on the LOH.

    Don't forget, List<T> allocates space based on an algorithm (currently, x*2). It isn't what you put in the list that takes the space, but how much Capacity the list currently has.

    The LOH allocation limit is an implementation detail of the runtime and could potentially change. It's interesting to see how it works, but don't build anything that relies on how it currently works.