Mega Swarm + AS3 optimizations
I’m still working on the flocking code I blogged about earlier.
I wanted to get more flock objects on screen. But my nearest neighbour detection code was VERY SLOW. In the old version each flock object would do a closest neighbor check by for looping through EVERY OTHER ENTITY on screen. The number of calculations would increase exponentially as the number of flock entities increased. This set a limit of about 200 entities before things started to slow down.
So I decided to add a broad level distance detection level. My first attempt got me up to about 700, before things started to slow down. Which was not bad but I was sure I could do better. At this point my friend William stepped in and essentially re-wrote my code 3 times over (William is a math major, and a super smart guy). One of his broad hit level schemes let me get up to 2000 entites on screen at once (on my home computer). The version I posted here shows 1200.
See the mega swarm in action after the break.
So, what have I learned from all of this?
First of all, I've learned that I still have a lot to learn 🙂
More practically: I've found that dynamically creating named objects are very, very slow:
//Don't do this ever. entityContainer["entity_" + entityID] = createElement;
My use of named objects led to huge slow downs in the first few versions of the swarm. (I thought it would make adding and removing objects easier, but I didn't consider how much it would bog the app down). It's much faster to just make a big array, and worry about coming up with an efficient array manager (I have some thoughts on this already).
Next, it's extremely beneficial to use a code profiler. William wrote one just for the swarm and I hope to use it for some of my other projects to figure out where the bottlenecks are.
A code profiler allows you to see how much time each piece of your code takes to execute from there you can decide where to target your efforts.
So anyway, I learned so much from this project, and I'm not done with it just yet!
You can find the source for the older Boids implementation here. I don't feel comfortable posting the newest version as it's a horrible mess.
February 6th, 2009 at 7:01 pm
Hi
First off, the swam app looks very interesting I haven’t had a chance to dig into your code but I’m looking forward to learning form it.
Secondly, have you had a look into object pooling? It may open up more avenues for optimization since the app generates a large number of identical objects.
Shane McCartney has an interesting post over at his blog, Lost In Actionscript.
Check it out at
http://www.lostinactionscript.com/blog/index.php/2008/10/30/object-pooling-in-as3/
Cheers