Last active
August 29, 2015 14:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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