for-loop vs. for-in-loop vs. native forEach for arrays with gaps (v40)

Revision 40 of this benchmark created on


Description

Testing the speed of iterating various sized arrays with straight for-loop or with a for-in-loop over its keys or using the native Array.forEach() API.

The difference with other tests is that these arrays contain 'gaps' i.e. do not have all their array slots in the range 0..array.length filled with values.

Note: all arrays have the same array.length!

Setup

// setup `arr` array ('small/tiny')
      var arr = ['1', true, false, "", undefined, "", void 0, null, 2, 18.5936];
      
      // testing for having deleted keys in array
      delete(arr[3]);
      
      // setup `arr2` array ('medium gap')
      var arr2 = arr.slice(0);
      var j = 1;
      arr2[arr2.length + j] = Math.round(Math.random());
      
      // setup `arr3` array ('big gap')
      var arr3 = arr2.slice(0);
      var k = 5000;
      arr3[arr3.length + k] = Math.round(Math.random());
    
      // pad the arrays to length of arr3
      var len = arr3.length;
    
      for (var i = arr.length; i < len; i++) {
        if ((i % 10) === 3) continue;  // tiny gaps
        arr[i] = Math.round(Math.random());
      }
    
      for (var i = arr2.length; i < len; i++) {
        if ((i % (j + 10)) < (j - 10)) continue;  // medium gaps
        arr2[i] = Math.round(Math.random());
      }
    
      arr[len] = Math.round(Math.random());
      arr2[len] = Math.round(Math.random());
      arr3[len] = Math.round(Math.random());
    
    // and we're testing hammer hammer spam spam

Test runner

Ready to run.

Testing in
TestOps/sec
big gap array: for-loop
for (var m = 0, len = arr3.length; m < len; m++) {
  arr3[m];
}
ready
big gap array: for-in-loop
for (var m in arr3) {
  if (arr3.hasOwnProperty(m)) {
    arr3[m];
  }
}
ready
big gap array: native forEach
function process(item) {
  item;
}
arr3.forEach(process);
ready
small gap array: for-loop
for (var m = 0, len = arr2.length; m < len; m++) {
  arr2[m];
}
ready
small gap array: for-in-loop
for (var m in arr2) {
  if (arr2.hasOwnProperty(m)) {
    arr2[m];
  }
}
ready
small gap array: forEach
function process2(item) {
  item;
}
arr2.forEach(process2);
ready
tiny gap array: for-loop
for (var m = 0, len = arr.length; m < len; m++) {
  arr[m];
}
ready
tiny gap array: for-in-loop
for (var m in arr) {
  if (arr.hasOwnProperty(m)) {
    arr[m];
  }
}
ready

Revisions

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