Array.indexOf vs For loop (v5)

Revision 5 of this benchmark created on


Preparation HTML

<script>
  var elem,
      i = 0,
      allElements = document.getElementsByTagName("*"),
      haystack = [];

  // Sizzle Expr.find["TAG"]
  while ( (elem = allElements[i++]) ) {
    if ( elem.nodeType === 1 ) {
      haystack.push( elem );
    }
  }
</script>

<script>
  var result,
      lowIndex = haystack[2],
      highIndex = haystack[ haystack.length - 2 ],
      notFound = document.body.appendChild( document.createElement("noscript") ),
      nativeIndexOf = [].indexOf,
      simpleIndexOf = function( elems, elem ) {
        var i = 0,
        len = elems.length;
        for ( ; i < len; i++ ) {
          if ( elems[i] === elem ) {
            return i;
          }
        }
        return -1;
      };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Not found (simple)
result = simpleIndexOf( haystack, notFound );
ready
High index (native)
result = nativeIndexOf.call( haystack, highIndex );
ready
High index (simple)
result = simpleIndexOf( haystack, highIndex );
ready
Not found (native)
result = nativeIndexOf.call( haystack, notFound );
ready
Low index (native)
result = nativeIndexOf.call( haystack, lowIndex );
ready
Low index (simple)
result = simpleIndexOf( haystack, lowIndex );
ready

Revisions

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