How much memory does an array of objects in C # consume?

Suppose that we previously created three objects A, B, C from the class D; now the array defines, as shown below: D [] arr = new D [3]; arr [0] = A; arr [1] = B; arr [2] = C;

Does the array really contain references to objects or does it have a separate copy?

+4
source share
5 answers

C # highlights link types and value types.

A reference type is declared using the word class . Variables of these types contain references, so the array will be an array of references to objects. Each reference is 4 bytes (on a 32-bit system) or 8 bytes (on a 64-bit system).

The value type is declared using the word struct . Values ​​of this type are copied every time you assign them. An array of type values ​​contains copies of the values, so the size of the array is equal to the size of the structure times the number of elements.

Usually, when we say β€œobject”, we refer to instances of the reference type, so the answer to your question is β€œyes”, but remember the difference and make sure that you do not accidentally create a large array of large structure.

+2
source

An array of reference types contains only references.

In 32-bit application links, 32 bits (4 bytes), and in 64-bit application links, 64 bits (8 bytes). This way you can calculate the approximate size by multiplying the length of the array by the reference size. (There are also a few extra bytes for internal variables for the array class, and some extra bytes are used to manage memory.)

+5
source

You can look at the memory occupied by the array using WinDBG + SOS (or PSSCOR2). IIRC, an array of reference types is represented in memory by its length, and then links to its elements, that is, its exact size PLATFORM_POINTER_SIZE * (array.Length + 1)

+2
source

The array is made up of pointers (32 bits or 64 bits) that point to objects. The object is a reference type, only value types are copied to the array itself.

0
source

As @Yves said, it has object references. An array is a block of memory, such as C. So the size of sizeof (element) * count + the amount of memory needed for oop.

0
source

All Articles