Last active
January 30, 2018 14:58
-
-
Save pec1985/daab8a50b9b7ad24d8af to your computer and use it in GitHub Desktop.
Array indexOf vs 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
function Pe(){}; | |
var len = 1000000; | |
var half = len / 2; | |
var array = []; | |
var last = new Pe(); | |
while(len--) { | |
array.push(new Pe()); | |
} | |
array.push(last); | |
(function(){ | |
var d = new Date().getTime(); | |
var i = array.indexOf(last); | |
console.log('(indexOf) Index: ' + i + '\tmilliseconds: ' + (new Date().getTime() - d)); | |
})(); | |
(function(){ | |
var d = new Date().getTime(); | |
var index = -1; | |
for(var i = 0, len = array.length; i < len; i++) { | |
if(array[i] === last) { | |
index = i; | |
break; | |
} | |
} | |
console.log('(for loop) Index: ' + index + '\tmilliseconds: ' + (new Date().getTime() - d)); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For loop is by far, faster