- read

What is Alignment? A Small Change for a Huge Impact

Phuong Le (@func25) 147

GO OPTIMIZE

Photo by Hal Gatewood on Unsplash

In this talk, I’m going to walk through how struct memory layout works and cover concepts like alignment, offsets, and padding.

“Ugh, why do we need to learn about these boring struct details?”

I get it, at first this seems a little boring. But to show why these details actually matter for performance, let’s look at the below example.

We’ve got two structs here containing the same fields, just ordered differently:

type StructA struct { // 32 bytes
A byte
B int32
C byte
D int64
E byte
}

type StructB struct { // 16 bytes
B int32
A byte
C byte
E byte
D int64
}

Okay, get this, even though both structs have the exact same fields, structA takes up 32 bytes. But StructB only uses half that space which is 16 bytes.

How Does Memory Layout Work? — blog.devtrovert.com

Let’s say you have 50 structA instances. That'll eat up 1600 bytes (1.6 kB) of memory. Not too bad, right? But get this - those same 50 StructB instances would only use 800 bytes (0.8 kB).

I know 50 doesn’t sound massive, but imagine this at a larger scale, with bigger structs and all. That difference can really start to impact your memory usage and performance in a hidden way.

What is alignment?

When experts mention alignment, they really mean the “required alignment” or “alignment guarantee” for a type.

What does that mean? Well, say a type has an alignment value of N bytes. The compiler will enforce a rule that any variables of that type must live at a memory address that’s a multiple of N.

If this does not make sense to you, let’s look at the int32 type which has an alignment of 4 bytes. This means int32 variables must be stored at memory addresses that are multiples of 4. So…