Array.indexOf vs For loop

JavaScript performance comparison

Revision 5 of this test case created by

Preparation code

<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>
    

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Not found (simple)
result = simpleIndexOf( haystack, notFound );
pending…
High index (native)
result = nativeIndexOf.call( haystack, highIndex );
pending…
High index (simple)
result = simpleIndexOf( haystack, highIndex );
pending…
Not found (native)
result = nativeIndexOf.call( haystack, notFound );
pending…
Low index (native)
result = nativeIndexOf.call( haystack, lowIndex );
pending…
Low index (simple)
result = simpleIndexOf( haystack, lowIndex );
pending…

Compare results of other browsers

Revisions

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

0 Comments