Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage of dynamic type in c#

Whether does dynamic-type use more memory size, than relevant type?

For example, does the field use only four bytes?

dynamic foo = (int) 1488;
like image 682
Palindromer Avatar asked Feb 06 '23 08:02

Palindromer


1 Answers

Short answer:

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

Long Answer

A dynamic type will be stored as an object but at run time the compiler will load many more bytes to make sense of what to do with the dynamic type. In order to do that, a lot more memory will be used to figure that out. Think of dynamic as a fancy object.

Here is a class:

class Mine
{
}

Here is the overhead for the above object on 32bit:

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

A total of 12 bytes needs to be allocated to it since the smallest reference type on 32bit is 12 bytes.

If we add one field to that class like this:

class Mine
{
    public int Field = 1488;
}

It will still take 12 bytes because the overhead and the int field can fit in the 12 bytes.

If we add another int field, it will take 16 bytes.

However, if we add one dynamic field to that class like this:

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

It will NOT be 12 bytes. The dynamic field will be treated like an object and thus the size will be 12 + 12 = 24 bytes.

What is interesting is if you do this instead:

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

An instance of Mine will still take 24 bytes because even though the dynamic fields is only a boolean, it is still treated like an object.

On a 64bit machine, an instance of Mine with dynamic will take 48 bytes since the smallest reference type on 64 bit is 24 bytes (24 + 24 = 48 bytes).

Here are some gotchas you should be aware of and see this answer for size of object.

like image 176
CodingYoshi Avatar answered Feb 08 '23 17:02

CodingYoshi