This lesson is locked. Login or Subscribe for more access!

Field Alignment

Duration: 3 mins

Learn why field alignment can be important for making applications use less memory and be more performant.

Instructor

Matt Boyle

Share with a friend!

Transcript

When writing Go programs, the order of struct fields can impact memory efficiency due to alignment and padding.

Go automatically aligns struct fields to match your CPU architecture, ensuring efficient access, but it can sometimes introduce unnecessary padding. This can be costly, especially in programs where you're using large amounts of structs and memory. If you're writing a high-performance application, this is something you should care about.

So what do I mean by alignment and how it affects structs? Let's write a bit of code to figure this out.

I'm going to declare a struct type. Here, I've created a struct that likely has bad alignment. I'll print its size using the unsafe package, which helps us inspect memory layout.

When we run this, we see that the struct is using 24 bytes of memory. This might surprise you. If you know the expected sizes, you might think it should be much less. This happens due to padding. Let's see if we can optimize this by reordering the fields.

I'll move field B to a different position and rerun the code. Look at that—we just saved 8 bytes of memory simply by reorganizing the fields.

Why does this happen? Each data type in Go has an alignment requirement. This means it must be stored at a memory address that is a multiple of its size or a defined boundary.

For example, int64 values, which are usually 8 bytes, must be stored at a memory address that is a multiple of 8. If a smaller field is placed before a larger one, Go adds padding to align it correctly, increasing the overall size.

So does this mean you always need to think about alignment when writing Go code? Not necessarily. The compiler does a good job of managing this for most use cases, but if you're working on high-performance applications or memory-intensive workloads, optimizing struct layout can save significant space.

By understanding struct alignment and how Go handles padding, you can write more memory-efficient code. Next time you're working with structs, consider field order—it might just improve performance without any extra computation!