Codementor Events

JavaScript/EcmaScript loop benchmark (incl. for/for-of/while/forEach/map)

Published Mar 27, 2021
JavaScript/EcmaScript loop benchmark (incl. for/for-of/while/forEach/map)

JavaScript's forEach(), map(), reduce() are quite handy for iterating a data set, but you may not know they have performance issue when deal with big volumes of data, and there are better ways to do so.

https://jsben.ch/EAlKw

Result

Codes

Execute before every test

var arr = Array(1000000).fill(null);
var dosmth;

for - Uncached length

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

for - Cached length

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

for.. of

for (let val of arr) { dosmth = val;
}

while - Uncached length

let i = 0; while(i < arr.length){ dosmth = arr[i]; ++i;
}

while - Cached length

let i = 0;
const len = arr.length; while(i < len){ dosmth = arr[i]; ++i;
}

forEach

arr.forEach(el=>(dosmth = el));

map

arr.map(el=>(dosmth = el));
Discover and read more posts from Neo TAN
get started
post commentsBe the first to share your opinion
Show more replies