Skip to content

Instantly share code, notes, and snippets.

@pec1985
Last active January 30, 2018 14:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pec1985/daab8a50b9b7ad24d8af to your computer and use it in GitHub Desktop.
Save pec1985/daab8a50b9b7ad24d8af to your computer and use it in GitHub Desktop.
Array indexOf vs for loop
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));
})();
@pec1985
Copy link
Author

pec1985 commented Oct 13, 2014

For loop is by far, faster

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment