今天,分析了一下怎样建对象,才能节省内存。
总结如下:
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
12byte
struct c1
{
int a;
}
{
int a;
}
class c2
{
int a;
}
{
int a;
}
/
16byte
16byte
struct c1
{
int a;
bool b;
}
{
int a;
bool b;
}
class c2
{
bool b;
int a;
}
{
bool b;
int a;
}
/
20byte
struct c1
{
bool c;
int a;
bool b;
}
20byte
struct c1
{
bool c;
int a;
bool b;
}
16byte
struct c1
{
int a;
bool b;
bool c;
}
struct c1
{
int a;
bool b;
bool c;
}
16byte
class c2
{
bool b;
int a;
bool c;
}
class c2
{
bool b;
int a;
bool c;
}
///
12byte
12byte
struct c1
{
short a;
bool b;
bool c;
}
{
short a;
bool b;
bool c;
}
class c2
{
bool b;
short a;
bool c;
}
{
bool b;
short a;
bool c;
}
///
16byte
16byte
struct c1
{
short a;
bool b;
bool c;
bool e;
}
{
short a;
bool b;
bool c;
bool e;
}
class c2
{
bool b;
short a;
bool c;
bool d;
}
//
16byte
{
bool b;
short a;
bool c;
bool d;
}
//
16byte
struct c1
{
short a;
bool b;
bool c;
{
short a;
bool b;
bool c;
short f;
short g;
}
short g;
}
class c2
{
bool b;
short a;
bool c;
{
bool b;
short a;
bool c;
bool d;
bool e;
bool f;
bool g;
}
bool e;
bool f;
bool g;
}
//
20byte
struct c1
{
short a;
bool b;
bool c;
20byte
struct c1
{
short a;
bool b;
bool c;
short f;
short g;
short g;
bool h;
}
}
class c2
{
bool b;
short a;
bool c;
{
bool b;
short a;
bool c;
bool d;
bool e;
bool f;
bool g;
bool e;
bool f;
bool g;
bool h;
}
}
数组的空项只占4byte 远远小空对象的12byte
///
16 byte
class c2
{
bool b;
short a;
bool c;
16 byte
class c2
{
bool b;
short a;
bool c;
c2 d;
}
}
20byte
struct c1
{
short a;
bool b;
bool c;
struct c1
{
short a;
bool b;
bool c;
c2 d;
c2 e;
c2 e;
}
36byte =12+24
class c2
{
bool b;
short a;
bool c;
class c2
{
bool b;
short a;
bool c;
c1 d;
c1 e;
}
c1 e;
}