Which one is faster? Why?
var messages:Array = [.....]
// 1 - for
var len:int = messages.length;
for (var i:int = 0; i < len; i++) {
var o:Object = messages[i];
// ...
}
// 2 - foreach
for each (var o:Object in messages) {
// ...
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
From where I’m sitting, regular
forloops are moderately faster thanfor eachloops in the minimal case. Also, as with AS2 days, decrementing your way through aforloop generally provides a very minor improvement.But really, any slight difference here will be dwarfed by the requirements of what you actually do inside the loop. You can find operations that will work faster or slower in either case. The real answer is that neither kind of loop can be meaningfully said to be faster than the other – you must profile your code as it appears in your application.
Sample code:
Results:
Edit: To improve the comparison, I changed the inner loops so they do nothing but access the collection value.
Edit 2: Answers to oshyshko’s comment:
forloop now has an implicit type conversion. I left assignments out of my loops to avoid that.Of course one could argue that it’s okay to have an extra cast in the
forloop because “real code” would need it anyway, but to me that’s just another way of saying “there’s no general answer; which loop is faster depends on what you do inside your loop”. Which is the answer I’m giving you. 😉