# A decent design for handling large creation/deletion of random objects?

So I was attempting a 'Hit the X' game (e.g Toss the turtle, spank the monkey) in which an uncontrollable object travels across the screen in hopes of hitting certain objects and avoiding others.

My dilemma is how to efficiently create and destroy these objects with respect to the character - that is, if the player is at, say, (90,34), all objects whose x position is less than 90 are garbage collected while more objects are generated at x > 90 or 100.

The only solution I could think of was to: randomly populate a tree that organizes by X values at the start of each round and to simply trim off the leaves at every so frames - if the player hits a certain spot, in which the tree is looking scrawny, start adding some more random objects on.

But this seems inefficient and unwieldy. Does anyone have any suggestions?

• Unless you'll be creating/destroying 100-500 of these per animation step, I doubt you'll see any performance problems with a straightfroward implementation (e.g., without optimizations). What is your target platform and how many objects are you dealing with? – Todd Lehman Feb 27 '12 at 6:20
• You might want to have a look at polygonal datastructures. It's a library with implementations for all commonly used data-structures, even implementations for object-pools, which is probably what you want. – bummzack Feb 27 '12 at 7:41

Unless I am misunderstanding the situation you are asking about, this seems like premature optimization to me. I would say implement whatever technique is most straightforward for you. You can optimize it later if you start having performance issues, but for such a simple game I wouldn't expect to have a bottleneck with the creation of random objects.

• Agreed... I'd venture to say you've spent more time thinking through this than you will ever save in CPU time. – notlesh Feb 27 '12 at 4:01

What you want to do is have an boolean active property on your objects that determines whether or not they get drawn/can be affected.

You then create a pool of the objects (i.e. define and initialize an array of inactive (active == false) objects as large as the most objects you'll have active at one time). Then, when you want to spawn a new object, find an active == false object in the array and set it's properties and then set it to active = true. When you want to get rid of objects, loop the array to see what objects have an x value less than 90 (or whatever) and set their active = false.