JS: For loop vs Array.indexOf (v277)

Revision 277 of this benchmark created by Adrian Bartholomew on


Description

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

Preparation HTML

<script>
  var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9];
</script>

Setup

Array.prototype.myio = function(search) {
      for (var i = 0, _len = this.length; i < _len; i++) {
        if (this[i] === search) {
          return i;
        }
      }
      return -1;
    }
    Array.prototype.myio3 = function(search) {
      for (var i = 0, needle; needle = this[i]; i++) {
        if (needle === search) {
          return i;
        }
      }
      return -1
    }
    
    Array.prototype.myio4 = function(search) {
      return this.indexOf(search);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
For loop cached
ar.myio(40)
ready
For loop assigned
ar.myio3(40)
ready
indexOf
ar.myio4(40)
ready

Revisions

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