JS: For loop vs Array.indexOf (v20)

Revision 20 of this benchmark created 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];
        Array.prototype.jsperfIndexOf = function(element,index) {
          //taken from the very guts of V8 and simplified [!]
          var length = this.length;
          if (length == 0) return -1;
          if (index == undefined) {
            index = 0;
          } else {
            // If index is negative, index from the end of the array.
            if (index < 0) {
              index = length + index;
              // If index is still negative, search the entire array.
              if (index < 0) index = 0;
            }
          }
          var min = index;
          var max = length;
          // Lookup through the array.
          if (!(element == undefined)) {
            for (var i = min; i < max; i++) {
              if (this[i] === element) return i;
            }
            return -1;
          }
          // Lookup through the array.
          for (var i = min; i < max; i++) {
            if (this[i] == undefined && i in this) {
              return i;
            }
          }
          return -1;
        }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
var a = ar.indexOf(40);
ready
indexOf
ar.jsperfIndexOf(40)
ready

Revisions

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