Lurking in the great code depths, by Jacob H. Hansen

Improving your component-based framework: Part 2, component storage

September 11, 2008 23:06 by Jacob H. Hansen

Continuing the series, I will talk a bit about how to store and keep track of your precious components. You probably saw the green database icon on the diagrams from part one without any explanation of what it did, and how it did it. That is what I’ll be talking about in this post.

So, first of all, why do we even need to care about how our components are stored? Can’t we just put them all into one big list? Well, if the system aims to be dynamic and data-driven it is quite likely that you will, at some point, be spending time trying to find one, or several, components of a specific type. If all your components were just stuck in one huge list, you would have to run through all of these every single time just to find the right one.

Obviously this seems unnecessary, and that’s exactly what it is. However, keeping such a list on the side might still have its uses (maybe you want to loop through every single component that is alive).

Implementing your component storage wisely will make a big difference on the performance of your entire system.

Building the database structure

Assuming that the unnecessary game-object layer has been cut away, it is suddenly less complex to maintain the (huge) list of components, and still have a constant O(1) lookup time on components, though at the cost of a minimal amount of memory (I say minimal, but I also haven’t written any AAA titles with 1249182764 components alive).

So, to achieve this, I suggest that you utilize one, or several, hashtables to handle your component storage. This hashtable should, for each guid, contain another hashtable that holds the types, and the actual component references.

Supporting C# example:

Dictionary<guid, Dictionary<Type, Component>> database;

I visualize this as seen on the following diagram:

 



As mentioned, utilizing a hashtable allows you to get fast lookups with little effort. But when coupled with the power of generics you can easily get an elegant, safe and speedy solution for component querying up and running quickly. Though the need for querying support is debatable, it allows for a more dynamic approach to using and building your components.

I will talk further on the use of generics and querying in a later post!




Comments

xzeth on December 2. 2008 08:07

how about a sample implementation using XNA..

Ryan on December 5. 2008 14:01

I would love to see more as I am tyring to use a similar type of design in my engine. Smile

Add comment