JS: For loop vs Array.indexOf (v145)

Revision 145 of this benchmark created by KAS on


Description

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

Setup

var ar = ["em", "strong", "i", "b", "a", "small", "abbr", "cite", "dfn", "kbd", "samp", "bdo", "q", "sub", "sup"],
      needle = "small",
      run;

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
run = function() {
  for (var i = 0; i < ar.length; i += 1) {
    if (ar[i] === needle) {
      return i;
    }
  }
  return -1;
};
ready
indexOf
run = function() {
  return ar.indexOf(needle);
};
ready
Better While loop
run = function() {
  var i = ar.length;
  while (--i >= 0) {
    if (ar[i] === needle) {
      return i;
    }
  }
  return -1;
};
ready

Revisions

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