PDA

View Full Version : Optimising loops?



PranQ
February 23rd, 2006, 07:12 PM
I ( I admit quickly) looked through the tutorial secion and didnt find an answer to this.

example of my for statements: for (var i:Number = 0; i < Array.length; i++) {

I have a game with several for loops, some are even nested within each other! this causes major lag as you continue playing, mainly because the loops are based on arrays which grow as the game plays. Such as enemys spawning and such, but since the enemys die. I dont need the loop to go through it for the dead enemies, so my question is, since the loop is relying on the .length property of the array, how i can make it so the for statement only goes through the last 5 enemies that have been spawned?

freeskier89
February 23rd, 2006, 07:23 PM
Make the loop go backwards from the end of the array.

for (var i:Number = Array.length-1; i > Array.length-6; i--) {

That should make it go through the last 5 if I understand you right

PranQ
February 23rd, 2006, 07:44 PM
that works, thank you

freeskier89
February 23rd, 2006, 07:47 PM
No problem ;)

TheCanadian
February 23rd, 2006, 08:05 PM
You should splice a item from the array when it's not needed anymore :)

PranQ
February 23rd, 2006, 09:08 PM
yea, but can you splice associative arrays? i never tried

TheCanadian
February 23rd, 2006, 09:15 PM
All arrays are associative but I get what you are saying. You can't do it they way you would with an instance of the Array class but you can either use the delete statement (to remove variables), removeTextField (to, well, remove text fields) and removeMovieClip (to remove movie clips)

PranQ
February 23rd, 2006, 09:24 PM
those were what i was using before, but they left the index number leaving flash to run lots of loops using undefined variables, so thats why i asked this, and working backwords worked

TheCanadian
February 23rd, 2006, 09:37 PM
But it looks like you are using an instance of Array class so you can just use the splice method.

PranQ
February 23rd, 2006, 09:53 PM
yes, the splice method is preferable for most of the loops, and i have put it in, but working backwards is the only way that will work for one of the loops

TheCanadian
February 23rd, 2006, 10:00 PM
Alright I'll take your word for it :)