Skip to main content
Known Participant
July 27, 2011
Answered

Array.length in a for loop

  • July 27, 2011
  • 5 replies
  • 3908 views

Okay here is the debate. I like to use array.length in my for loop to keep my code cleaner to read. Is there any huge downside to this? For example will it speed up things greatly if i store the length in a var one time?

Thanks for any insight!!

This topic has been closed for replies.
Correct answer Andrei1-bKoviI

Math speaks for itself.

Using variable instead of length is more than 20 times faster. So, conclusion, undoubtedly, is that setting variable to array length and then using it in a loop is the way to go, especially on large iterations.

Here is a benchmark test:

Without length:

var st:Number = getTimer();
for (var i:int = 0; i < 1000000; i++ ) {     
}
trace(getTimer() - st);

Trace returns something around 12 ms

With array length:

var array:Array = [];
for (var j:int = 0; j < 1000000; j++)
{
     array.push(1);
}
var st:Number = getTimer();
for (var i:int = 0; i < array.length; i++)
{
     
}
trace(getTimer() - st);

Trace returns about 220-224 ms

This is a clear confirmation of what to use.

5 replies

Inspiring
July 28, 2011

And even without benchmark testing, it is just logical that using preset variable instead of Array.length must be faster. Array.length is a property that resides in a different scope - this is already slower to read its value from a different scope (while declared variable is residing in the same scope). in addition, length is NOT A PURE PROPERTY but an accessor (setter/getter). Thus, because methods are inherently slower than properties - it makes it even slower to read length.

In a loop on EVERY ITERATION length is read afresh - it is not indexed. Hence, obviously, using a distinct variable is more efficient.

Known Participant
July 28, 2011

Thanks for the tests!

That said, this is with a million objects in the array. I have under 350. Also, @ 1,000 items in the array they both don't calculate to a millisecond (ie 0 vs 0). At 10,000 items it is it's mixed between 0 vs 1 and sometimes 0 vs 2. If it's a matter of 2 milliseconds I'll take more readable code all day long.

Thanks everyone for you help on this! For large iterations it's definetly more valuable to use a scoped var.

Inspiring
July 28, 2011

Well, I strongly believe (which is confirmed by experience) that choosing code readability over performance is an EXTREMELY bad idea and quite a deviation from best OOP practices. I would NEVER EVER take readable code over performance. I hope you realize it sooner than later.

Milliseconds and microseconds pile up very quickly. Remember that average 30 frame per second rate gives you only 33 milliseconds to process code. IN EVERY SCOPE.

Andrei1-bKoviICorrect answer
Inspiring
July 28, 2011

Math speaks for itself.

Using variable instead of length is more than 20 times faster. So, conclusion, undoubtedly, is that setting variable to array length and then using it in a loop is the way to go, especially on large iterations.

Here is a benchmark test:

Without length:

var st:Number = getTimer();
for (var i:int = 0; i < 1000000; i++ ) {     
}
trace(getTimer() - st);

Trace returns something around 12 ms

With array length:

var array:Array = [];
for (var j:int = 0; j < 1000000; j++)
{
     array.push(1);
}
var st:Number = getTimer();
for (var i:int = 0; i < array.length; i++)
{
     
}
trace(getTimer() - st);

Trace returns about 220-224 ms

This is a clear confirmation of what to use.

Community Expert
July 28, 2011

If you use Array.length as for loop condition Flash has to evaluate Array.length on each iteration again and again. This is slow, waste of resource, and not elegant There are no difference in the code "readability" here so there are no reasons you should use inefficient method specifically.

Using Andrei's example (but with a larger number):

var array:Array = [];
for (var i:uint = 0; i < 9000000; i++) {
     array.push(1);
}

var st:uint;

st = getTimer();
for (var j:uint = 0; j < array.length; j++) {
     // loop 1
}
trace("loop 1", getTimer() - st);

st = getTimer();
var len:uint = array.length
for (var k:uint = 0; k < len; k++) {
     // loop 2
}
trace("loop 2", getTimer() - st);

// trace
// loop 1 682
// loop 2 112

If you store the length in a var it's much faster.

How I usually do is to create a var to store the length in the for loop initialisation so the code is cleaner:

st = getTimer();
for (var l:uint = 0, len2:uint = array.length; l < len2; l++) {
     // loop 3
}
trace("loop 3", getTimer() - st);

// trace
// loop 3 111

The speed is the same as the loop above.

You can also assign the length to the iterater at the initialisation, then subtract 1 on each iteration:

st = getTimer();
for(var m:uint = array.length - 1; m > 0; --m){
    // loop 4
}
trace("loop 4", getTimer() - st);

// trace

// loop 4 118

Participant
July 28, 2011

Unfortunately, this issue is exacerbated logarithmically when you nest

loops. I did a getTimer() style test with nested loops over two small

arrays (100 elements) and saw a 95% performance difference. 95%!!!!

There are lots of AS optimization techniques that actually do make

code less readable, this isn't one of them. Bitwise shifting is far

more performant than the Math class, for example, but far harder to

read. If you draw an arbitrary 'readability' line with this technique,

how will you ever let yourself take advantage of more advanced

techniques?

Known Participant
July 27, 2011

That's my thinking exactly. Can any Adobe employees confirm that this is the best approach?

Ned Murphy
Legend
July 27, 2011

It's doubtful you'll find any Adobe employees around here to confirm anything.  Adobe employees don't use these user-to-user forums as a general rule.

Known Participant
July 27, 2011

Ahhh thanks Ned!

Ned Murphy
Legend
July 27, 2011

Having the added weight of another variable might have a greater impact than looking at the array for a property  One downside I see goes the other way... what if the array changes... what extra code do you need to have that variable keep tracking the changing length.  I'd stick with the array.length.

Participating Frequently
July 27, 2011

Feel free to use array.length, there's no benefit to storing it in a different variable. In fact, it's better to use array.length, taking into account that your code will be more readable, and you have one less variable. Just make sure you don't change the length of the array in the loop (that would be bad practice anyway.)