The fastest way is bypassing the index.
An example on jsfiddle .
function fillArray(cnt) { let res = []; for (let i = 0; i < cnt; i++) { res.push(i); } return res; } var arr = fillArray(5000000); var t = null; t = Date.now(); arr.forEach(async function(e, i) { arr[i] += 1; }); console.log('time forEach async', Date.now() - t); t = Date.now(); arr.forEach(function(e, i) { arr[i] += 1; }); console.log('time forEach', Date.now() - t); t = Date.now(); for (let e of arr) { e += 1; // здесь мы значение массива не меняем } console.log('time let of', Date.now() - t); t = Date.now(); for (let i = 0; i < arr.length; i++) { arr[i] += 1; } console.log('time for with index', Date.now() - t);
Update
In fact, the test turned out to be quite controversial, because in the loop we change the array, and this operation can have different execution times in terms of speed.
Therefore, it would be more logical to start an empty loop, with no action inside.
As pointed out in the @Grundy comments, Edge is faster.
An example on an empty jsfiddle loop.
function fillArray(cnt) { let res = []; for (let i = 0; i < cnt; i++) { res.push(i); } return res; } var arr = fillArray(5000000); var t = null; t = Date.now(); arr.forEach(function(e, i) { }); console.log('time forEach', Date.now() - t); t = Date.now(); for (let e of arr) { } console.log('time let of', Date.now() - t); t = Date.now(); var len = arr.length; for (let i = 0; i < len; i++) { } console.log('time for with index', Date.now() - t);
The most interesting thing to check results in Edge .
In the code above, even in Edge , index crawling is faster.
But there are 3 interesting nuances:
- if we remove the
let len = arr.length; , the code will work slower. - if we replace
let i = 0 with var i = 0 , the code will run slower. - if we add the array change code to all cycles, the index traversal will become slower.
I think we can conclude that Edge has poor code optimization.
Хотелось бы более быстрого выполнения кода- on arrays of a billion elements there can and will be a difference .... but on small ones that are used in the frontend - no difference - Aleksey ShimanskyregexpData.forEach(async function(e){if( e.test(str) ) console.log(e.exec(str));});(str = let change in the upper block) it is easy for you to make out what's what - Alex TvoyTrubafor(let i=0;i<arr.length;i++){console.log(arr[i]);}. - Stepan Kasyanenko