JS: For loop vs Array.indexOf vs index in Object (v235)

Revision 235 of this benchmark created by r00t3g on


Description

Testing speed of a standard for loop vs. Array.indexOf vs. inverse for loop vs. while loop vs. for with cached length.

Checking for 5000 in a 10000 index array for equal opportunity inverse.

Added a test case suitable for just checking a presence of some value in a set of values when there is no need to keep array type.

Preparation HTML

<script>
  var ar = [],
      ob = {};
  for (var i = 0; i < 10000; i++){
    /* 
     The idea is to flip keys with values to make the search 
     faster using in, thus we need to make values differ from keys
    */
    var v = i + Math.random() + ""; // And let's make them strings
    ar.push(v);
    ob[v] = i;
    var ref = ar[5000];
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
For loop
for (var i = 0; i < ar.length; i++) {
 if (ar[i] === ref) {
  break;
 }
}
ready
indexOf
var a = ar.indexOf(ref);
ready
inverse for-loop
for (var i = ar.length; i--;) {
 if (ar[i] === ref) {
  break;
 }
}
ready
while loop
var i = 0, l = ar.length;
while (i < l) {
 if (ar[i] === ref) {
  break;
 }
 i++;
}
ready
For loop cached
var l = ar.length;
for (var i = 0; i < ar.length; i++) {
 if (ar[i] === ref) {
  break;
 }
}
ready
In-check
var index = (ref in ob ? ob[ref] : -1);
ready

Revisions

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