JS: For loop vs Array.indexOf (v264)

Revision 264 of this benchmark created on


Description

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

Preparation HTML

<script>
  var ar = [
    'asset!0',
    'asset!11',
    'asset!15',
    'asset!16',
    'asset!20',
    'asset!21',
    'asset!22',
    'asset!28',
    'asset!4',
    'asset!7'];
</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()*10)];
var a = ar.indexOf2(key);
ready
while
var key = ar[Math.floor(Math.random()*10)];
var a = ar.indexOf3(key);
ready
indexOf
var key = ar[Math.floor(Math.random()*10)];
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.