Last Updated: October 04, 2020
·
2.584K
· daniellmb

JavaScript Looper

Q: How do you make a loop fast?

A: Do as little as possible inside the loop.

This is not the best way to write a loop (I'll explain why below)

for (var i = 0; i < bigArray.length; i++) {
    doWork(bigArray[i]);
}

The above typical loop pattern does these steps on each iteration:

  1. Property lookup (bigArray.length)
  2. Value comparison (i < bigArray.length)
  3. Value comparison of the control condition (true | false)
  4. Numeric increment (i++)
  5. Array item lookup (bigArray[i])
  6. Function call (doWork(...))

Here is an improved loop pattern:

var i = bigArray.length;
while(i--) {
    doWork(bigArray[i]);
}

It only does these steps on each iteration:

  1. Value comparison of the control condition (true | false)
  2. Numeric decrement (i--)
  3. Array item lookup (bigArray[i])
  4. Function call (doWork(...))

The improved design pattern has these benefits:

  • Combines the control condition with the decrement operation.
  • Minimizes property lookups (by looking up the array length once)
  • It's 50% to 60% faster than the first version!

It's fast, compact and easy to read, I use it every chance I can (but it's not always the best choice due to the fact that it loops in reverse).

These are "micro optimizations", but when you need to squeeze out every last frame per second, each choice you make adds up (especially on mobile devices and older browsers).

Related protips:

javascript foreach

4 Responses
Add your response

When using a for loop you'd probably cache the length inline and do this:

for (var i = 0, l = ary.length; i < l; i++) {
  ...
}
over 1 year ago ·

It's fast, compact and easy to read, I use it every chance I can (but it's not always the best choice due to the fact that it loops in reverse).

You can always Array.reverse() the data first.

var i = bigArray.reverse().length;
while(i--) {
doWork(bigArray[i]);
}

over 1 year ago ·

@leemachin yep there are a lot of variations on how to optimize looping, thanks for sharing yours.

over 1 year ago ·

@lastguest good point, but while the Array.reverse() method is native (fast), it isn't free, so depending on the size of the array it could degrade performance.

over 1 year ago ·