JS: For loop vs Array.indexOf (v265)

Revision 265 of this benchmark created by Gabriel on


Description

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

Preparation HTML

<script>
var ar = [];
  for (var i = 0; i < 1000000; i++)
 {
ar[i] = 'asset!' + i;
 }
</script>

Setup

Array.prototype.indexOf2 = function (x) {
    for (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] === key) return i;
    }
    return -1;
    };

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
var key = ar[Math.floor(Math.random()*1000000)];
var a = ar.indexOf2(key);
ready
while
var key = ar[Math.floor(Math.random()*1000000)];
var a = ar.indexOf3(key);
ready
indexOf
var key = ar[Math.floor(Math.random()*1000000)];
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.