C#中动态类型的内存使用情况 [英] Memory usage of dynamic type in c#

查看:158
本文介绍了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;

推荐答案

简短回答:

不.实际上,它将在32位计算机上使用12个字节,在64位计算机上使用24个字节.

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

长期回答

一个dynamic类型将被存储为一个对象,但是在运行时,编译器将加载更多字节,以了解使用dynamic类型该怎么做.为了做到这一点,将使用更多的内存来解决这一问题.将dynamic视为 fancy 对象.

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.

这是一堂课:

class Mine
{
}

以下是上述对象在32位上的开销:

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

总共需要分配12个字节,因为32位的最小引用类型是12个字节.

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;
}

由于开销和int字段可以容纳12个字节,因此它仍将占用12个字节.

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

如果我们添加另一个int字段,则将占用16个字节.

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

但是,如果我们像这样向该类添加一个dynamic字段:

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

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

为12个字节.动态字段将被视为object,因此其大小将为12 + 12 = 24个字节.

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;
}

Mine的实例仍将占用24个字节,因为即使动态字段只是一个布尔值,它仍然被视为object.

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.

在64位计算机上,具有Mine实例将占用48个字节,因为64位的最小引用类型是24个字节(24 + 24 = 48个字节).

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.

这篇关于C#中动态类型的内存使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆