forEach vs for len vs for in vs for of vs babel for of loops

Benchmark created by aretecode on


Setup

var testData = [];
  for (var i = 0; i < 100; i++) {
    testData.push(i);
  }

Test runner

Ready to run.

Testing in
TestOps/sec
forEach
// forEach
var res = 0;
testData.forEach(function(x) {
  res += x;
});
ready
for
// for 
var res = 0;
for (var i = 0; i < testData.length; i++) {
  res += testData[i];
}
ready
for cache length optimized
// for optimized 
var res = 0;
for (var i = 0, len = testData.length; i < len; i++) {
  res += testData[i];
}
ready
reduce
// reduce 
var res = testData.reduce(function(sum, x) {
  return sum + x;
}, 0);
ready
while
// while
var res = 0;
var i = testData.length;
while (i--) {
    res += testData[i];
}
ready
for in
// for in 
var res = 0;
for (var data in testData) {
  res += testData[i];
}
ready
for of
// for of
var res = 0;
for (var data of testData) {
  res += testData[i];
}
ready
for of babel
// for of babel
var res = 0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;

try {
  for (var _iterator = testData[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
    var value = _step.value;

    console.log(value);
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    res += testData[i];
    if (!_iteratorNormalCompletion && _iterator.return) {
      _iterator.return();
    }
  } finally {
    if (_didIteratorError) {
      throw _iteratorError;
    }
  }
}
ready

Revisions

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

  • Revision 1: published by aretecode on