Performance optimisation: is removing sprites far from player smart?

I'm working on a side scroller, which right now places obstacles and platforms at the start of the level. I'm considering a performance function that runs every second: remove() sprites that are further than 2 screen-lengths away from the player, add them again when the player comes closer.

ā†’ Will the garbage collector remove sprites that are not added, even when there are references to them, like in an array? Even when they have custom functions and variables inside of the sprite?
ā†’ If so, is there a way to keep them "ready" and added, but taking less performance? Does just hiding them or removing their collision rectangle help?



Read up on garbage collection: objects aren't killed off unless they and their variables, functions and tables are set to nil. So it's safe to remove() a sprite far away from the player to improve performance, because its update() won't be called and it will be ignored by moveWithCollisions(), right?

I'm using C. I pre-create a bunch of sprites, then add() and remove() them as they're needed. As far as I can tell, when the sprites are remove()d from the screen they are not processed.

For example, I create a bunch of alien bomb sprites that are kept removed. When one of my aliens needs a bomb-sprite I find an idle one, re-position it, then add() it to the display list. When the bomb goes off-screen, it gets removed and set to idle again.

This seems like an efficient approach, as allocating memory from the heap can be an expensive operation.

So thus, I reckon your approach is a good one.

1 Like

Thanks! Re-using obstacles and platforms from a pool as I need them might be even better for memory than doing only the ones that matter, that's a good idea.

Currently have a decent platform engine running, with all the small conditions stable, like "don't fall back down after landing on a platform after sliding against it when jumping from a previous platform" :slight_smile: