DEV Community

Cover image for Golang Writing memory efficient and CPU optimized Go Structs

Golang Writing memory efficient and CPU optimized Go Structs

Satyajiijt Roy on July 26, 2022

A struct is a typed collection of fields, useful for grouping data into records. This allows all the data relating to one entity to be neatly encap...
Collapse
 
ankush981 profile image
Ankush Thakur

🔥🔥🔥

Collapse
 
skysolderone profile image
Skysolderone

thanks

Collapse
 
gusga profile image
Gustavo Giménez

Great way to explain this topic. congrats

Collapse
 
deadlock profile image
Satyajiijt Roy

Thanks

Collapse
 
isudarsan profile image
SUDARSAN

Thanks a lot of your detailed explanation. Helpful alot

Collapse
 
deadlock profile image
Satyajiijt Roy

Glad to know!!

Collapse
 
arpitvarshneya profile image
Arpit Varshneya • Edited

Didn't get why empty pad of 7 bytes, 7 bytes and 4 bytes respectively were added to make the sum of 8 bytes by complier? Why 8?

Collapse
 
deadlock profile image
Satyajiijt Roy

Because, the current version of the standard Go compiler, the alignment guarantees of other types may be either 4 or 8, depends on different build target architectures. This is also true for gccgo.

Collapse
 
fracasula profile image
Francesco Casula

Interesting article. A linter might be a good idea in this case. It could make writing memory optimized structs quite easy. It can be integrated in CI as well instead of having to always rely on code reviews etc...

Collapse
 
drsensor profile image
૮༼⚆︿⚆༽つ

Thanks for the write up! TIL, go compiler doesn't auto align the struct. I wonder if I should fit my struct to 128bit, hoping that the compiler will optimize some of r/w fields operation with SIMD instructions 🤔

Collapse
 
motaman profile image
MB

Great write-up!. Thanks so much for sharing your findings so clearly :)

Collapse
 
deadlock profile image
Satyajiijt Roy

Thanks @motaman

Collapse
 
__d27f373b517a4 profile image
Виталий Мих

Here's a great ready-made solution:github.com/t34-dev/go-field-alignment