从字节对齐方式的角度看内存管理

背景:字节对齐是编译器来处理的,但是我们依然需要适当关注;字节对齐是为了提高内存系统性能(字节对齐可以减少内存访问的次数)
主流的字节对齐方法

一、结构体中调整成员变量的顺序
struct test{
int a;
char b;
int d;
short d;
}
占用空间:4+4+4+4 =16
调整为
struct test{
char b;
short d;
int c;
int a;
}
占用空间:4+4+4 =12 > ``
二、添加伪代码

 #pragma pack(1) /*一字节对齐*/
 struct test{
  int  a;
   char b;
   int d;
   short d;
 } 
 #pragma pack() /*还原默认对齐*/

占用空间 4+1+4+2 =11
三、使用align

> struct test{
>   int  a;
>   char b;
>   int d;
>   short d;
> }__attribute__((__aligned__(1))) 
posted @ 2022-02-26 14:33  行者行者行者  阅读(47)  评论(0)    收藏  举报