This page looks best with JavaScript enabled

Is it really useful to cache array length in a for loop?

 ·   ·  ☕ 2 min read

It is a commonly recommended practice to cache array lengths while doing for loops and get better performance. Seriously, is that a thing though?

Typical for loop

In a typical for, you calculate length, iterate and you are done.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const arr = new Array(1e7).fill(1);
let j = 0;

console.time("for-test");
for (let i = 0; i < arr.length; i++) {
  j += i;
}
console.timeEnd("for-test");

// 17.850ms 25.295ms 20.860ms

Cache for loop

Rather than use a typical array length condition, you first find the length and use that variable in all comparisons. This should save time to call the length method each and every time.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
const arr = new Array(1e7).fill(1);
let j = 0;

console.time("for-test");
for (let i = 0, len = arr.length; i < len; i++) {
  j += i;
}
console.timeEnd("for-test");

// 19.655ms 18.382ms 23.186ms

At least for me, there was no observable difference in caching the array length for 1e7 values in the array. I could not see anything different for other types of arrays like strings, boolean, or an object. The comparison needs better tests on better servers - a thing to do for some other time.

But, overall the array length by itself may not really be contributing significantly to performance problems in the overall scheme of things. Or, V8 may have been optimised the heck out to really care about the humble array length when used in for comparison.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things