This page looks best with JavaScript enabled

Faster Loops in Javascript

 ·   ·  ☕ 2 min read

We have come to appreciate the performance and readability of the ol’ for loop. But, just how much should we be appreciating the performance?

We already did a huge scientific study on different avatars of for. This is the time that we do another highly ineffective test for different types of loops so that we can prove nothing to no one.

Consider this simple array.

1
const arr = new Array(1000).fill("v");

We will measure the time taken to go through the array and print every element.

Simple for
1
2
3
4
5
6
7
const arr = new Array(1000).fill("v");

console.time("loop");
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
console.timeEnd("loop"); // 359.868ms
‘Efficient’ for

A lot of smart guys recommend using a variable to store the array length value in a for. This should potentially cut down the time to lookup whether the array should end.

1
2
3
4
5
console.time("loop");
for (let i = 0; (len = arr.length), i < len; i++) {
  console.log(arr[i]);
}
console.timeEnd("loop"); // 383.720ms 378.136ms 470.718ms

More modern runtime engines would have probably optimized this already. I did not find any difference while running Node 12.

while loop

From my previous experience with while, I did not expect to see much difference.

1
2
3
4
5
6
7
console.time("loop");
let i = arr.length;
while (i > 0) {
  console.log(arr[i]);
  i--;
}
console.timeEnd("loop"); // 390.582ms 311.583ms 429.276ms
do-while loop

It will be crazy to expect anything less with a do-while when we already had while.

1
2
3
4
5
6
7
console.time("loop");
let i = arr.length;
do {
  console.log(arr[i]);
  i--;
} while (i > 0);
console.timeEnd("loop"); // 372.058ms 341.528ms 455.252ms

Results

Simple for Efficient for while do-while
359.868ms
344.918ms
410.166ms
383.720ms
378.136ms
470.718ms
390.582ms
311.583ms
429.276ms
372.058ms
341.528ms
455.252ms

Since we started with the rock-bottom expectation to not prove anything, we have achieved our stated objectives.

But, we did see the usage of console.time() instead of the node-specific perf_hooks to measure performance. So, it is that we easily exceeded 100% there.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things