Many thanks to @themaour for sharing this tip on Twitter

TIL that in Go, struct size depends on how underlying types were defined.

struct {
	a bool
    b int32
    c string
    d string
}

The size of the struct above is is different from the one down below

struct {
	b int32
    c string
    d string
    a bool
}

Why is that? Well, think of memory as consisting of segments of certain size, where, if the amount of data you fill the segment with is bigger than the current remainder of the segment, the data will get written onto the next segment. The remaining space (a.k.a, padding) remains unused, and every instance of your struct might have some portion of unused padding when initialised.

There is a great online resource where you can see this by providing a sample struct definition. Let’s see what it shows for struct #1:

and struct #2:

Think of this the next time you get to process a slice of 1 mln instances of a given struct.

Resources

The Lost Art of Structure Packing
This page is about a technique for reducing the memory footprint of programs in compiled languages with C-like structures - manually repacking these declarations for reduced size. To read it, you will require basic knowledge of the C programming language.