Benchmarking Array Traversal in Javascript: How to Go Backwards the Fastestโ€‚by@wagslane

Benchmarking Array Traversal in Javascript: How to Go Backwards the Fastest

There are many ways to traverse an array in JavaScript. In this benchmark, we will look at five different ways and the pros and cons of each. These benchmarks were run in a Chrome browser on Codepen. Results will vary by browser/interpreter. The first two times running this after a fresh browser load are quite slow, but then it gets blazingly fast. This is because at each iteration the loop checks against a constant 0 zero value instead of calling the array's.length property.
image
Lane Wagner HackerNoon profile picture

Lane Wagner

Founder of Boot.dev. Whining about coding sins since 2011. Committing coding sins for the same.

twitter social icongithub social iconlinkedin social iconfacebook social icon

There are many ways to traverse an array in JavaScript. In this benchmark, we will look at five different ways and the pros and cons of each. Keep in mind that these benchmarks were run in a Chrome browser on Codepen. Results will vary by browser/interpreter.

For a working example of these benchmarks, take a look at this codepen:

All benchmarks we ran on an array of 1000000000 items.

1st: Vanilla JS - Backwards

for (let i = arr.length-1; i>=0; i--){}

~ 30 milliseconds

Going backwards is faster than going forward! This is because at each iteration the loop checks against a constant 0 zero value instead of calling the array's .length property. Doesn't mean you should do it though... its weird and hard to follow cognitively.

2nd: Vanilla JS - Forwards

for (let i = 0; i< arr.length; i++){}

~39 milliseconds

3rd: ES6 forEach()

arr.forEach(function(element) {});

~180 milliseconds

Slow but with a more convenient syntax, nothing surprising here.

4th: jQuery Each

$.each(arr, function( index, value ) {});

~225 milliseconds

Eeeeeew... jQuery. Convenient if you live in 2010. Very Slow.

Wildcard: For..Of ES6

image
for (const item of arr){}

First and second time running: 153 Milliseconds
Third+ times running : ~18 milliseconds

This is weird, and I'm not sure how to explain it. Maybe someone smarter than me can tweet me the answer @wagslane . The first two times running this after a fresh browser load are quite slow, but then it gets blazingly fast. I'm assuming there are some es6 optimizations under the hood that kick in.

Subscribe to Qvault:ย https://qvault.io



react to story with heart
react to story with light
react to story with boat
react to story with money
L O A D I N G
. . . comments & more!