Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ifraixedes/7347d73c12a4c58a4087 to your computer and use it in GitHub Desktop.
Save ifraixedes/7347d73c12a4c58a4087 to your computer and use it in GitHub Desktop.
Perfomance difference between looping an array using Array methods and simple boring for loop
'use strict';
var i, tmp, initTime, stopTime;
var arr = Array(99999999);
// Iterate using `for` loop
tmp = 0;
initTime = Date.now();
for (i = 0; i < arr.length; i++) {
tmp += i;
}
stopTime = Date.now();
console.log('Iterate using boring `for` loop: %s ms', stopTime - initTime);
// Iterate using reduce and declaring function straightaway in the reduce function call
tmp = 0;
initTime = Date.now();
tmp = arr.reduce(function (prev, curr, i) {
return prev + i;
}, tmp);
stopTime = Date.now();
console.log('Iterate using Array.reduce with function declaration into the function call: %s ms', stopTime - initTime);
// Iterate using reduce but declaring function outside and passing the reference to reduce
function reduceFn (prev, curr, i) {
return prev + i;
}
tmp = 0;
initTime = Date.now();
tmp = arr.reduce(reduceFn, tmp);
stopTime = Date.now();
console.log('Iterate using Array.reduce with function declaration outside the function call: %s ms', stopTime - initTime);
// Iterate using forEach and declaring function straightaway in the reduce function call
tmp = 0;
initTime = Date.now();
arr.forEach(function (value, i) {
tmp += i;
});
stopTime = Date.now();
console.log('Iterate using Array.forEach with function declaration into the function call: %s ms', stopTime - initTime);
// Iterate using forEach but declaring function outside and passing the reference to reduce
function forEachFn (val, i) {
tmp += i;
}
tmp = 0;
initTime = Date.now();
arr.forEach(forEachFn);
stopTime = Date.now();
console.log('Iterate using Array.forEach with function declaration outside the function call: %s ms', stopTime - initTime);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment