对象的内存消耗

今天,分析了一下怎样建对象,才能节省内存。
 
总结如下:
1。struct不会自动排列成员,而class会,对于类,无需费心排列。
2。空对象(class、struct 不含基本类型)必然占用 12byte
3。当class struct 成员变量总和小于4byte ,那么 还是只占12byte(和空的一样大)
 
4。class 内部最小自动对齐是1byte,外部是4byte;bool至少耗费8bit(内部)
5。class 内部引用class对象,一个占4byte
6。class 内部使用struct对象,一个占12byte(有时会略小):这就是等于新建了一个对象。
 
7。数组平均一个空项4byte:一个引用而已。
 
总结:新对象(struct成员,或new object),必然占12byte以上,而引用只占4byte
 

//
12byte
    struct c1
    {
    }
    class c2
    {
    }
/
12byte
    struct c1
    {
        int a;
    }
    class c2
    {
        int a;
    }
/
16byte
    struct c1
    {      
        int a;     
        bool b;
    }
    class c2
    {
        bool b;
        int a;
    }
/
20byte
    struct c1
    {
        bool c;
        int a;     
        bool b;
    }
16byte
    struct c1
    {       
        int a;     
        bool b;
        bool c;
    }
16byte
    class c2
    {
        bool b;
        int a;
        bool c;
    }
///
12byte
    struct c1
    {       
        short a;     
        bool b;
        bool c;
    }
    class c2
    {
        bool b;
        short a;
        bool c;
    }
///
16byte
    struct c1
    {       
        short a;     
        bool b;
        bool c;
        bool e;
    }
    class c2
    {
        bool b;
        short a;
        bool c;
        bool d;
    }
//
16byte
    struct c1
    {       
        short a;     
        bool b;
        bool c;
        short f;
        short g;
    }
    class c2
    {
        bool b;
        short a;
        bool c;
        bool d;
        bool e;
        bool f;
        bool g;
    }
//
20byte
    struct c1
    {       
        short a;     
        bool b;
        bool c;
        short f;
        short g;
        bool h;
    }
    class c2
    {
        bool b;
        short a;
        bool c;
        bool d;
        bool e;
        bool f;
        bool g;
        bool h;
    }

数组的空项只占4byte 远远小空对象的12byte
///
16 byte
    class c2
    {
        bool b;
        short a;
        bool c;
        c2 d;
    }
20byte
    struct c1
    {       
        short a;     
        bool b;
        bool c;
        c2 d;
        c2 e;
    }
36byte =12+24
    class c2
    {
        bool b;
        short a;
        bool c;
        c1 d;
        c1 e;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值