TechWorkRamblings

by Mike Kalvas

202412221201 Struct of Arrays

In programming, changing an array of structures to a structure of arrays can often make a drastic difference in computation speed and efficiency. It's particularly effective when the whole struct does not need to be processed when performing an action on the collection.

// Array of structs = Vec<Cheese>
pub struct Cheese {
    pub smell: u64,
    pub color: (u64, u64, u64),
    pub with_mushrooms: bool,
    pub name: String,
}

// Struct of arrays
pub struct CheeseVec {
    pub smell: Vec<u64>,
    pub color: Vec<(u64, u64, u64)>,
    pub with_mushrooms: Vec<bool>,
    pub name: Vec<String>,
}

There is no one specific reason to lay things out like this, but some circumstantial reasons are cache-locality (if using sparse parallel arrays) or packing SIMD lanes with the homogenous data type in the array.1


  1. AoS and SoA. (2024). In Wikipedia. https://en.wikipedia.org/w/index.php?title=AoS_and_SoA&oldid=1229841268