Better way of doing this?

Monkey Targets Forums/Android/Better way of doing this?

DPbrad(Posted 2012) [#1]
At the moment, I am still fairly new to Monkey so this may be an issue regarding which data type I am using, but I was just wondering;

1) I made an app where you touch the screen, and a "bullet" object is created, added to a stack, given a random x-speed and y-speed, then moved every OnUpdate until it is offscreen, when it is then removed from the stack.

This was alright for <20 bullets, but once you started creating 20+ bullets, my Android phone would start lagging quite badly.

So, I discovered that creating a New Bullet object every time you click was a bad idea, so did the following;

2) Created a pool of 100 pre-created "bullets" and added them to a stack, along with a new variable which tracks the next index in the stack (Resets to 0 when it reaches the end of the stack), the Bullet class now has a "isUsed:Bool" which is defaulted to false. If you touch the screen, the isUsed is set to true, by a function which also sets its postion, dX & dY, and its colour.

Once the bullet is off-screen again, its isUsed bool is set to false, and all its variables are zeroed.

This is generally quite faster, and I can now get to about 50 bullets with little to no lag, anything above 70 and it does start to lag a bit.

I was wondering if its possible to optimize this any further? I still have various other things to add, and if my app is already starting to lag after just a few objects on screen, with further objects still to be added, it seems like it may be too slow.


Dima(Posted 2012) [#2]
Mark has made a very good post regarding object pooling at the end of this thread: http://www.monkeycoder.co.nz/Community/posts.php?topic=860#7000

the linked list approach pre-allocates objects and when you need more than pooled it will allocate more on the fly - a very optimized approach.


Samah(Posted 2012) [#3]
If the order of the bullets doesn't matter, you could use indexed pointers into an array. Have a look at the way the Diddy particle system works. That handles many thousands of particles with pretty much no lag. The slowest part is DrawImage :-)

http://code.google.com/p/diddy/source/browse/trunk/src/diddy/psystem.monkey


DPbrad(Posted 2012) [#4]
Thanks for the replies guys. I tried using the Linked List style system and it was still quite slow, although the double buffering method improved the speed quite nicely.

I am downloading Diddy right now so will give that a go and see how things are done there. Cheers guys.