6.3. Optimize Data Layout

After making sure the program is algorithmically optimal, we turn to memory related optimization areas. The first such area is to ensure that data is laid out in memory in an optimal way.

Generally speaking, data needs to be packed to utilize memory well. It also needs to be sorted in such a way as to utilize spatial reuse. With spatial reuse, we mean that data being used in the same code context should be placed next to each other.

The following situations are but some that can cause wasted space in cache lines:

[Tip]Tip
Use correct data types
[Tip]Tip
Sort record fields according to size and usage pattern.
[Tip]Tip
Organize data to avoid mixing read-only and write fields in the same cache line. If many fields needs to be updated at the same time, place them in the same cache line.
[Tip]Tip
Avoid dynamic allocation of small objects, and consider using custom allocators
[Tip]Tip
Use data structures that pack data efficiently
[Tip]Tip
Avoid "pointer chasing" and indirections