I often read in the ECS game engine documentations that is a good architecture for using cpu cache wisely.
But I can't figure how we can benefit from cpu cache.
If components are saved in an array (or a pool), in contiguous memory, it's a good way to use cpu cache BUT only if we read the components sequentially.
When we use systems, they need entities list which are list of entities that have components with specific types.
But these lists give the components in a random way, not sequentially.
So how to design a ECS to maximize the cache hit ?
EDIT :
By example, a Physic system needs an entities list for entity that has the RigidBody and Transform components (There is a pool for RigidBody and a pool for Transform components).
So its loop for updating entities will be like this :
for (Entity eid in entitiesList) {
// Get rigid body component
RigidBody *rigidBody = entityManager.getComponentFromEntity<RigidBody>(eid);
// Get transform component
Transform *transform = entityManager.getComponentFromEntity<Transform>(eid);
// Do something with rigid body and transform component
}
The problem is that the RigidBody component of entity1 can be at the index 2 of its pool and the Tranform component of entity1 at the index 0 of its pool (because some entities can have some components and not the other and because of adding / deleting entities / components randomly).
So even if components are contiguous in memory, they are read randomly and so it will have more cache miss, no ?
Unless there is a way to prefetch the next components in the loop ?