Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ryan961 opened this issue Jan 23, 2024 · 0 comments
Open
Labels
Golang All things associated with Go. Reading Daily Reading

Comments

@ryan961
Copy link
Owner

ryan961 commented Jan 23, 2024

🤖 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.

@ryan961 ryan961 added Golang All things associated with Go. Reading Daily Reading labels Jan 23, 2024
@ryan961 ryan961 changed the title Go Fact: Zero-sized Field at the Rear of a Struct Has Non-zero Size Go Struct: Zero-sized Field at the Rear of a Struct Has Non-zero Size Jan 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Golang All things associated with Go. Reading Daily Reading
Projects
None yet
Development

No branches or pull requests

1 participant