For/While Loop vs indexOf (v123)

Revision 123 of this benchmark created on


Setup

var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9, 9, 2, 3, 4, 5, 6, 7, 8, 9];
      
    for (var i = 0; i < 9999; i++)
    ar.push(Math.round(Math.random()*9999));
      
      function indexOfFor(ar,v){
        for (var i = 0,l=ar.length; i < l; i++) {
         if (ar[i] === v) {
            return i;
          }
        }
        return -1;
      }
      
      function indexOfWhile(ar,v){
        var i=0,a;
        while (a=ar[i++]) {
         if (a === v) {
            return i-1;
          }
        }
        return -1;
      }
      
      function indexOf(ar,v){
        return ar.indexOf(v);
      }

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
var a = indexOfFor(ar,40);
ready
While Loop
var a = indexOfWhile(ar,40);
ready
indexOf
var a = indexOf(ar,40);
ready

Revisions

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