I'm building a game with XNA at the moment, and I currently have my game object components set up like so:
class Character : GameComponent
{
public int health, state;
public float speed;
}
etc. Since making a menu system, I've played around with data container type objects, say I have a base class of DataContainer, and then subclasses like IntContainer, FloatContainer. Depending on their subclass, they return their contained data type. I'm wanting to hook up this menu system to the components, so that I can easily edit them, I'm wondering if I should change my components to also adopt this model of holding generic data containers instead of explicitly typed data, like so:
class Character : GameComponent
{
public DataContainer[] data;
public int health()
{
return (data[0].getValue());
}
}
I could keep appropriately named methods as above, so getting a value by name in code would still be simple. It will take a bit of work to swap my engine over to this method of data storage, so I'm wondering if anyone has input, does the more generic method affect performance in any measurable way? Is calling two methods to get a value worse than grabbing the value directly?
Calling a method will always be slightly slower than getting a field directly, but this will not have a noticiable effect unless they are called hundreds of times per frame. (Ex: You probably shouldn't use
getTile(x, y)
in your rendering code, lighting code, whatever applies)I must say using
DataContainer
s for all of your properties seems a bit unconventional, however they are certainly useful for serializing your data.If you want to use them, instead of complicating your code and adding methods to get and set them, you can use properties. (Take a look at this tutorial)
Properties let you control access to a private member, call a function, or compute logic, while still looking like regular variables.
Here is an example in your case:
This way you can simply change your fields over to properties, while implementing your logic. Also note, as I said earlier, how methods do cause a very, very slight amount of time to be used. Properties are really methods beneath the hood, so calling get or set will be the same as calling a method. This, combined with searching the
data
array for the specified member, will be very fast, but not as fast as a field. So, with that said, you shouldn't notice any lag, but if the game is big enough their may be a slight amount (Although it shouldn't bother you for now, really only applies if you were to add indexing to your tile array or something, just a thought)If you were to ask me, I would say just keep it simple and go with the standard approach using fields and properties in your program, no need to introduce custom DataContainers, in fact, in my opinion you shouldn't need to.