Principle
About Golang The writing order of field in the same struct will be different for different memory allocation sizes. The main reasons are as follows: The field memory allocation within a struct is based on 4 B and must be exclusive at 4B.
Example
type A1 struct { a bool b uint32 c bool d uint32 e uint8 f uint32 g uint8}
Calculate the amount of memory that A1 needs to occupy:
- First, the 1th 4B in the a,a is a bool type, occupies 1B, the remaining 3B
- Then look at B is UInt32, Occupy 4B, the remaining 3B, so offset to the next 4B space, then we will find 3B did not put things, was wasted
- Down, A1 to occupy 28B of space
According to 1, 22 steps are easy to see, there is a lot of wasted space.
Optimization:
type A2 struct { a bool c bool e uint8 g uint8 b uint32 d uint32 f uint32}
- First, the 1th 4B in the a,a is a bool type, occupies 1B, the remaining 3B
- C is bool, take 1B, put the remaining 2B after
- D is uint8, Occupy 1B, put the remaining 1B after
- Turn down
This can make memory usage much higher.