Pre Allocation of Interfaced Game Objects?

Started by
4 comments, last by EJH 13 years, 6 months ago
Hey all, I've run into a bit of coder's block on my initialization of game objects, which i'll sum up right here.

Lets say we have 3 classes.
class IObject{void Update() = 0;};class CObjOne : public IObject{void Update() {}};class CObjTwo : public IObject{void Update() {}};


Now given a constant number of total max objects, what is the best way to handle memory allocation not knowing #obj 1, #obj 2, just the total number of IObjects available?

Any Ideas?
Advertisement
I don't quite follow your question. If you're talking about the memory needed for IObject itself, that will be allocated automatically in the instance of the parent class. If your interface object needs to do some sort of custom allocation on a per-instance basis, do that within its own constructor. If there are 3 Obj1 and 4 Obj2 creations, then your code will automatically call the IObject constructor 7 times.
i'm talking about pre allocating memory for obj one and obj two so during the main loop the application doesn't have to go through new and delete routines which can slow down a game.
If you don't want to spend too much time thinking about it, don't preallocate at all and let the free store handle it.

If you have some time to spend on the subject, create two independent memory pools (one for each object type) and preallocate the total number in both. This will waste twice as much memory, but it's fairly simple to set up and reasonably safe.

If you have a lot of time to spend on the subject, create a single memory pool that contains chunks of a size equal to the size of the largest of the two objects. This way, any chunk may be initialized as either type of object.

Of course, all of this assumes that you're overloading operator new to use the pooled memory (as opposed to pre-instantiating the objects, which is a lot worse in terms of code safety and maintenance).
You can use Boost Pool library or implement something similar but such preallocations are only needed in specific cases.
Quote:Original post by Denzin
i'm talking about pre allocating memory for obj one and obj two so during the main loop the application doesn't have to go through new and delete routines which can slow down a game.


You will see a performance benefit from pre-allocation if (a) there are a lot of objects and (b) they are created / destroyed often. So particle systems and projectiles are a good place to do it if you have a lot of them. There is no down side to pre-allocating everything else though and it is much harder to leak memory when you never delete things. =)

Also, if obj1 and obj2 are very different in functionality, considering allocating them in separate lists. It helps to avoid the "if(obj.type==X)" and switches that are hard to avoid in heterogeneous lists, especially when you get to collision and AI.

This topic is closed to new replies.

Advertisement