JS: For loop vs Array.indexOf (v260)

Revision 260 of this benchmark created on


Description

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

Setup

var str = "memory_expire";
    
    function indexOfFor(ar, v) {
      var i, l = ar.length;
      for (i = 0; i < l; i++) {
        if (ar[i] === v) {
          return i;
        }
      }
      return -1;
    }
    
    function indexOfWhile(ar, v) {
      var i = ar.length;
      while (i--) {
        if (ar[i] === v) {
          return i;
        }
      }
      return -1;
    }
    
    function strIndexOf(ar, v) {
      return ar.indexOf(v);
    }
    
    function strIncludes(ar, v) {
      return ar.includes(v);
    }
    
    function regexTest(ar, v) {
      var re = new RegExp(v);
      return re.test(ar);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
indexOfFor(str, "memory");
ready
While Loop
indexOfWhile(str, "memory");
ready
native indexof
strIndexOf(str, "memory");
ready
native includes
//strIncludes(str, "memory");
str.includes("memory");
ready
Regex test
/^memory/i.test(str);
ready
inline indexOf
str.indexOf("memory") !== -1;
ready
direct cmp
str === "memory" || str === "memory_expire";
ready
slice cmp
str.slice(0, 6) === "memory";
ready

Revisions

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