Golang defines the concept of byte alignment in the structure struct (appropriate adjustment of the field order can save a lot of memory)
The number of bytes occupied by each embedded type of Go (64-bit machine)
bool 1 byte
byte 1 byte
int 8 bytes
float32 4 bytes
float64 8 bytes
string 16 bytes
slice 24 bytes
map :8 bytes
As verification code:
There is a very strange phenomenon in which f0 only occupies 1 byte, but f1 does not start from offset 2, but starts from 8. This involves the concept of go byte alignment.
A 64-bit machine can only get 8 bytes of data at a time
The fields in the struct will be allocated a contiguous piece of memory to obtain the value of a field in the struct.
If the offset of the field is an integer multiple of 8 or an integer multiple of the bytes occupied by the type, the offset does not need to be calculated, then can be obtained quickly.
Therefore, go will padding the fields defined in the struct when compiling, so that the offset of the next field is an integer multiple of 8 or an integer multiple of the bytes occupied by the type to achieve the purpose of acceleration, so define the struct reasonably,To a certain extent, it can save a lot of memory.
Such as:
Just change the order of the structure fields, and the memory occupied is greatly reduced