JL. JL. - 1 year ago 105
C# Question

How are arrays handled in memory?

Given that an array is allocated a fixed area of memory, it makes complete sense that the length of the array is immutable.

Let's say I have Array[10] - this will allocate 10 slots of adjacent memory right? And it is because these slots are adjacent and at predetermined locations, indexed based lookups are quick.

But what if I'm putting complex types into my array, of uneven sizes. The actual objects in the array might be of the same type, but the data they hold can differ vastly in size.

How does .Net handle this? I would imagine it allocates non sequential memory to store the actual data in the objects but I would like an authoritative answer on this. For example - does it only use non sequential memory if the object exceeds a certain size? What if the object is constantly changing in size, will it keep trying to optimize a storage location?

Consider this class:

public class MyClass
public MyClass[] PotentiallyHugeNestedStructure

Now if I have an array of myclass and at runtime start allocating to sub arrays and sub arrays. I can end up with a vast collection of jagged arrays.

So how does .net handle this, in memory?

Answer Source

In arrays of reference types, each element in the array holds a reference that points to an object in the managed heap.

So there is absolutely no disadvantage of having an array of objects over an array of primitive types. You can access any object in the list through the index in a very fast manner.

The overhead of looking up the reference of the object found in that index is negligible (Since the reference is usually a number that represents an offset to a memory location).

The below image demonstrates arrays holding reference types vs arrays holding value types:

enter image description here

Image from : CLR Via C# by Jeffrey Richter

myControls is an array of objects, so each element holds either Null (by default) or a reference to an object (4 bytes for 32-bit systems and 8 bytes for 64-bit systems).

Side Note: The overhead specified in the picture contains information about the array:

  • Dimension
  • The lower bound of each dimension (0 is most cases)
  • The length of the array.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download