Jump to content

  • Log In with Google      Sign In   
  • Create Account


Nohup

Member Since 19 Mar 2004
Offline Last Active Feb 28 2013 10:40 AM
-----

#4893843 Cache friendly dynamic allocation

Posted by Nohup on 14 December 2011 - 08:18 AM

I think there's an issue with the use of the word "alignment" in your post.
That word has a slightly different meaning than what you're considering. It's more to do with the exact placement of something within the memory banks of a machine along certain boundaries (byte, word, page).

If I read you right, then you don't really care about exactly where a thing is placed.
You're more concerned that all the things you make are placed in an orderly manner, and tightly packed, to get better cache utilization.

If that's the case, then you were going along the right path with your thoughts of using a vector to store your components.
The problem with a vector is that all the types in a vector must be the same. And from your code-snippet, you were thinking more of using a common interface to a set of different derived classes (components).

Your code snippet shows that you want to store pointers to various types of components. That's a pretty common method. But I'm afraid, that it is unlikely that those components will ever be near each other in memory (cache coherent).

The best you're likely to get, is having all of your components of a certain type together in memory. For instance, the "Health" components can all be pre-allocated in a vector/array, and can be tightly packed together.
Your entities will store pointers to those components (as in your boost:unordered data structure).
Then, if you can structure your code to run all of the entitiy's "health" processing at the same time, your cache-utilization will be very good.
Do this for every component type, and you should get most of what you're looking for.

Now, managing a whole bunch of vectors for every component type might be a bit daunting. Every time an entity is destroyed, you will have to remove it's components from their storage vectors, or somehow mark them as free. That can be a bit of a pain, and could lead to a lot of bugs. My advice is to use a freelist or some pooling allocator to do the job for you.
(Game Programming Gems 4 has a good article on freelists, and boost::pool has a nice implementation that you could use to help manage the lifetimes of the components

Once you have all the components in their homogeneous vectors, you might start looking for a way to just iterate over all the components within those vectors, without even considering what entity they belong to.
Like the health example, you could check all the healths to see if any are <0, and if so look up that health's entity ID, and create a message for that entity to "die".
Lots of flexibility in this setup, it's a lot like what I've been toying around with for a while.

good luck.


PARTNERS