Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Two of the main systems I've seen in entity system tutorials are:

  • An Entities class with one array / [hash]map for each component, with indices corresponding to entity IDs.
  • A list of Entity structs, which have the components as fields, and possibly a pointer to a "cold" struct for less used components.

What are the reasons I would use the former over the latter, considering that the latter seems much easier to implement? Is there some advantage to having each attribute laid out contiguously in memory?

share|improve this question

closed as too broad by Lars Viklund, Alexandre Vaillancourt, Josh Petrie Jan 19 '16 at 16:41

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.If this question can be reworded to fit the rules in the help center, please edit the question.

up vote 5 down vote accepted

Is there some advantage to having each attribute laid out contiguously in memory?

It's better for cache locality of data access. Memory access is slowest part of all modern computing systems. As memory buses pull in multiple bytes in "cachelines" and most modern CPUs will prefetch memory that it detects are being accessed contiguously, keeping data that is used sequentially laid out in memory contiguously can have a signficant ans positive impact on efficiency.

That said, performance fetishism is not as useful as one might think, even in games. Plenty of big AAA games use something closer to the other technique you mention. There are places where cache locality of data is super important and places where it has little meaningful impact. Sometimes, ease of implementation or ease of maintenance will be more important than raw performance. A particle system is a place where every little bit of performance matters, for example, but an entity or component that only exists on a few dozen actors doesn't need to be maximally efficient.

A component-based architecture can use some ES-like techniques (a System that operates on contiguously-allocated data associated with Entity ids) for some components and can use a simpler container of objects for other components. There's no reason that one has to shoehorn oneself into the ES pattern for everything. A well-designed simple component architecture lets you use the appropriate design methodology for each component.

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.