"1) Which is better, negative loops (i.e. counting backwards in loops and checking if you reach zero) or foreach loops? Both options seem to be better than normal "for" loops, but which is faster of the two?"
By foreach, I'm going to assume you mean for..each or for..in loops. As Demian pointed out, forEach is pretty slow. For the others, doing a simple for loop is always quicker (you can early out of all of them except forEach I think) by just returning when you hit the check you need). Whether you do i++ or i-- makes no difference. for..each and for..in loops have their benefits though. for..in is the only way you can loop through Dictionary
and Object
objects, while for..each performs the cast for you, meaning you write less code. As in:
for each( var s:Sprite in this.m_mySpriteVector )
...
vs.
var len:int = this.m_mySpriteVector.length;
for( var i:int = 0; i < len; i++ )
var s:Sprite = this.m_mySpriteVector[i];
(on a side note, if you're doing a normal for loop, taking out the length is the best thing you can do to speed it up). Also note that the speed difference in for loops only really matter if they're large loops. If you're doing a loop of 10, then it doesn't really make any difference which one you pick.
"2) Which is better, using Numbers or ints?"
If you mean in loops, then always go for the int. In other general terms, use the class that represents what you need. If you only need whole numbers, then use int
or uint
. If you need decimals, then go for Number
. Use the wrong type and you do incur a small penalty, but not a huge one. Also, depending on what you hold in the variable, it mightn't be the type you think: http://jacksondunstan.com/articles/1357
"3) Does constant really decrease your performance?"
I've not really tested it, but probably not enough to really matter. Make a simple loop using 1,000,000 iterations or something and see if it makes a difference. Using a static const will incur a small penalty as it has to perform the class lookup, but it's not harsh
The final point to be made is to be careful about optimisation. Also have it in your head so you don't write code that sucks, but be careful where you apply it. Optimised code usually takes longer to write and is less readable than other code (the for..each loops being a good example).
Take into account where each piece of code is used. If it's what's called performance critical code - code that's called all the time (ENTER_FRAME, or common functions) then that's where you should focus your efforts. If it's a function that's called once, or not very often, then the time you spend optimising it will be a waste as you're getting very little benefit from it.