liveBook · Manning

Field ordering

As explained in 100 Go Mistakes and How to Avoid Them

Field ordering is the arrangement of a struct's fields to control its memory layout and reduce unnecessary padding.

A common mistake is placing small fields around a large, alignment-sensitive field. Go inserts padding so each field starts at a suitable address, and the resulting struct can consume more memory than its visible fields suggest. section 12.4

Reordering removes padding

This layout places an int64 between two bytes and occupies 24 bytes: type Foo struct { b1 byte i int64 b2 byte } Putting the int64 first lets the two byte fields share the remaining space, reducing the struct to 16 bytes: type Foo struct { i int64 b1 byte b2 byte } Explicit padding can represent the first layout, but reordering is usually the simpler fix when field order is not part of an external contract.

The benefit is not only lower per-value memory use. A slice of the compact struct fits more relevant fields into each cache line, so a loop that sums Foo.i may need fewer cache lines.

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains alignment guarantees, padding, field reordering, and cache-line effects with concrete struct layouts.
Examples
Compares byte-int64-byte and int64-byte-byte structs, then traces summation over a Foo slice.
What you can do after
Evaluate struct layouts and reorder fields to reduce padding when layout order permits.
How it connects
Connects data alignment, memory padding, structs, slices, and cache lines.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.