JS: For loop vs Array.indexOf (v267)

Revision 267 of this benchmark created by Gabriel on


Description

Testing speed of a standard for loop vs. Array.indexOf.

Preparation HTML

<script>
"use strict";
var ar = [];
  for (var i = 0; i < 249; i++)
 {
ar[i] = 'asset!' + i;
 }
Array.prototype.indexOf2 = function (x) {
for (var i = 0; i < this.length; i++) {
if (this[i] === x) return i;
}
return -1;
};

Array.prototype.indexOf3 = function (x) {
var i = this.length;
while(i--) {
  if(this[i] === x) return i;
}
return -1;
};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
var key = ar[Math.floor(Math.random()*249)];
var a = ar.indexOf2(key);
ready
while
var key = ar[Math.floor(Math.random()*249)];
var a = ar.indexOf3(key);
ready
indexOf
var key = ar[Math.floor(Math.random()*249)];
var a = ar.indexOf(key);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.