Loop Benchmark: for/for-in/for-of/forEach

JavaScript performance comparison

Test case created by shibukawa

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const array = new Array(1000000);
  for (let i = 0; i < 1000000; i++) {
      array[i] = (Math.random() * 100) | 0;
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
traditional for
let sum = 0;
for (let i = 0; i < 1000000; i++) {
    const value = array[i];
    sum += value;
}
pending…
for-in
let sum = 0;
for (const i in array) {
    const value = array[i];
    sum += value;
}
pending…
forEach
let sum = 0;
array.forEach(function(value) {
    sum += value;
});
pending…
forEach + arrow-function
let sum = 0;
array.forEach(value => sum += value);
pending…
forEach + arrow-function(no return)
let sum = 0;
array.forEach(value => {
    sum += value;
});
pending…
for-of
let sum = 0;
for (const value of array) {
    sum += value;
}
pending…
for-of (babel optimized/TypeScript)
var sum = 0;

for (var _i = 0, _array = array; _i < _array.length; _i++) {
  var value = _array[_i];
  sum += value;
}
pending…
for-of (babel standard)
var sum = 0;
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = array[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var value = _step.value;
      sum += value;
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return != null) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }
pending…

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

Compare results of other browsers

0 Comments