preface

struct  LGTruct1{
double a;
char b;
int c;
short d;
}struct1;
Copy the code
struct  LGTruct1{
double a;
int b;
char c;
short d;
}struct2;
Copy the code

NSLog(@”%lu-%lu”,sizeof(struct1),sizeof(struct2)); Output print size is 24-16; This leads us to wonder why both structures have the same member variables, but the output memory size is different. To figure this out, let’s look at a couple of things.

Bytes of C and OC types

Memory alignment principles

1. Data member alignment rules: The data member of a struct (or union), the first data member is placed at offset 0, and the starting position of each data member is from the size of the member or the size of the member’s children (as long as the member has children, such as arrays). Structure, etc.) (for example, if an int is 4 bytes on a 32-bit machine, it is stored from a multiple of 4.

2. Struct as members: If a struct contains members, then the members are stored at multiples of the size of the largest element in the struct.

3. Finishing off: the total sizeof a structure, the result of sizeof, must be an integer multiple of its largest internal member. What is lacking must be made up.

Example analysis

struct LGStruct3{ double a; //8 bytes [0-7] int b; //4 bytes [8-11] char c; //2 bytes [12-13] short d; //2 bytes [14 15] int e; //4 bytes [16 17 18 19] struct LGTruct1 STR; }struct3;Copy the code

Let’s analyze the structure LGTruct1; Structure members store LGTruct1 from an integer multiple of the size of the largest element inside them, which is 8; 24 is a multiple of 8, so 24 starts saving;

struct LGTruct1{ double a; //8 bytes [24 31] char b; //2 bytes [32 33] int c; [36 39] short d; //2 bytes [40 41]}struct1;Copy the code

Double A: [o-7] double A: [o-7] double A: [o-7] double A: [o-7] double A:

int b ; 4-byte structure members are stored from an integer multiple of the size of the largest internal element. [8] is an integer multiple of 4, so [8, 9, 10, 11]

char c; 12-2 bytes [13]

short d; 2 bytes [14 15]

int e; 4 bytes [16 17 18 19]

double a; //8 bytes [24 31]

char b; //2 bytes [32 33]

int c; //4 bytes start from multiple of 4 bytes [36 39]

short d; //2 bytes [40 41]

Finishing off: the total sizeof a structure, the result of sizeof, must be an integer multiple of its largest internal member. What is lacking must be made up.

The result 48 is an integer multiple of 8

NSLog(@”%lu”,sizeof(struct3)); The result was 48;

conclusion

Memory alignment Apple has a set of rules to improve storage efficiency and read security. In addition, Apple optimizes memory storage algorithms to reduce read times and ensure read security.