JS: For loop vs Array.indexOf (v52)

Revision 52 of this benchmark created on


Description

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

Setup

var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
    
    function indexOfLoop1(ar, key) {
    
      var len = ar.length;
      for (var i = 0; i < len; i++) {
        if (ar[i] === key) {
          return i;
        }
      }
    }
    
    function indexOfLoop2(ar, key) {
      for (var i = 0, current;
      (current = ar[i++]) !== undefined;) {
        if (current === key) {
          return i;
        }
      }
    }

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
var a = indexOfLoop1(ar, 10);
ready
indexOf
var a = ar.indexOf(10);
ready
for loop (true values)
var a = indexOfLoop2(ar, 10);
ready

Revisions

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