内存对齐
一、各种类型数据在内存中所占空间 二、示例
struct LGStruct1 {
double a; // 8 [0 7]
char b; // 1 [8]
int c; // 4 (9 10 11 [12 13 14 15]
short d; // 2 [16 17] 24
}struct1;
通过上图可看到内存地址需要位 8 的倍数。不足补 0,所以struct1的长度是 24.
struct LGStruct2 {
double a; // 8 [0 7]
int b; // 4 [8 9 10 11]
char c; // 1 [12]
short d; // 2 (13 [14 15] 16
}struct2;
通过上图对比,上下两个结构体内存占用长度实际是有所不同的。那实际结果是什么呢?我们来验证下。
NSLog(@"%lu - %lu",sizeof(struct1),sizeof(struct2));
24 - 16
由于 struct2 满足 2 个 8 位所以不用额外补齐占位所以比struct1 少用一个 8 位。 三、你猜猜看
struct LGStruct3 {
double a;
int b;
char c;
short d;
int e;
struct LGStruct1 str;
}struct3;
我们来看看
struct LGStruct3 {
double a; //8 [0 7]
int b; //4 [8 9 10 11]
char c; //1 [12]
short d; //2 (13 [14 15]
int e; //4 [16 17 18 19]
struct LGStruct1 str; //24 (20 21 22 23 [24 47]
}struct3;
最终结果是不是像我们想的一样呢?我们验证一下
NSLog(@"%lu",sizeof(struct3));
48
结果和我们预期一样。因为 LGStruct3这个结构体不算LGStruct1的情况下已经是 20,然后再加上LGStruct1这个结构体的 24,因为内存对齐的原因LGStruct1从 24 为开始。所以总计长度已经到了 48.并且 48 是 8 的倍数。不用再补0.所以struct3的数据长度为 48
四、总结
通过上面 3 个例子我们可以看到我们在创建变量的时候其实系统底层再帮我们做了很多事情,包括排序对齐等操作。但是系统不可能根据每个程序做单独的优化。这时候就需要利用我们的知识对内存调优。
不急不躁~我是不一样的烟火!!!