Dynamic type memory usage in C #

Does the dynamic type use more memory than the corresponding type?

For example, does a field use only four bytes?

dynamic foo = (int) 1488;
+4
source share
1 answer

Short answer :

No. It will actually use 12 bytes on a 32-bit machine and 24 bytes on 64 bits.

Long answer

The type dynamicwill be stored as an object, but at runtime the compiler will load many more bytes to figure out what to do with the type dynamic. To do this, much more memory will be used to determine this. Think of dynamichow deceptive an object.

Here is the class:

class Mine
{
}

32 :

--------------------------  -4 bytes 
|  Object Header Word    |
|------------------------|  +0 bytes
|  Method Table Pointer  |
|------------------------|  +4 bytes for Method Table Pointer

12 , 32 12 .

:

class Mine
{
    public int Field = 1488;
}

- 12 , int 12 .

int, 16 .

, dynamic :

class Mine
{
    public dynamic Field = (int)1488;
}

12 . object, , , 12 + 12 = 24 .

, :

class Mine
{
    public dynamic Field = (bool)false;
}

Mine - 24 , , - object.

64- Mine 48 , 64- - 24 (24 + 24 = 48 ).

, , . object.

+7

Source: https://habr.com/ru/post/1666960/


All Articles