ryan961 / memo

https://github.com/ryan961/memo/issues
Creative Commons Zero v1.0 Universal
0 stars 0 forks source link

Go Struct: Zero-sized Field at the Rear of a Struct Has Non-zero Size #5

Open ryan961 opened 7 months ago

ryan961 commented 7 months ago

🤖 AI Summary

This article revolves around a key concept in Golang - Zero-sized Type (ZST). This term refers to a type whose variables occupy no memory space. A common application of this can be seen in the use of map[string]struct{} to emulate a set structure efficiently. However, contrary to expectation, a ZST variable does not always occupy 0 byte of space. For instance, a struct named UserName consisting of a ZST field at the end takes up more space than a standard string. The reason, shared by the Go team on GitHub, is that a pointer to a ZST field, under particular circumstances, might point outside of the allocation, risking invalid access to unallocated memory by the Garbage Collector runtime. The additional bytes reserved by the Go compiler serve to avoid such issues. Reordering the ZST field to the middle of the struct eliminates the need for these extra bytes, therefore it's advised to place the ZST field in the middle of a struct.

🖇️ Details

đź”– Note

The issue of memory fragmentation within Go's struct seems to be a longstanding yet neglected issue. Nonetheless, in low-performance demanding scenarios, which represent 99% of our daily programming conundrums, the significance of this issue can turn out trivial indeed may be deemed as unnecessary. A recent discovery of a tool named betteralign provides an efficient way to address this issue. It allows for automatic struct field reordering without disturbing the struct layout, subsequently reducing the memory fragmentation within the struct—proving to be remarkably user-friendly and convenient.