Storage and Queries

Dense arrays, sparse sets, and iterating two component types together.

Part 2 of 3Updated

Components live in dense Vecs so iteration is a linear scan โ€” cache-friendly in a way that an Vec<Box<dyn GameObject>> never is.

pub struct Storage<T> {
    dense: Vec<T>,
    entities: Vec<Entity>,
    sparse: Vec<Option<u32>>,   // entity index -> dense index
}

The interesting part is querying two component types at once: iterate the smaller storage and look up the other. That single decision is most of the performance difference between a toy ECS and a usable one.

Getting &mut to two different component storages simultaneously requires either split_at_mut-style tricks or a runtime borrow check. This is the point where youโ€™ll understand why bevy_ecs is as complicated as it is.