for..of vs length vs for..in

Benchmark created by Jan Nowotny on


Setup

const array = [];
  let number = 10000;
  while(--number > 0) {
    array.push(number);
  }
  let element;

Test runner

Ready to run.

Testing in
TestOps/sec
length in loop
for (let i=0, length = array.length; i<length; i++) {
  element = array[i];
}
ready
for..of
for (const el of array) {
  element = el;
}
ready
for..in
for (const i in array) {
  element = array[i];
}
ready
length
for (let i=0; i<array.length; i++) {
 element = array[i];
}
ready
length before loop
let mylength = array.length;
for (let i=0; i<mylength; i++) {
  element = array[i];
}
ready
length and i declaration before loop
const mylength = array.length;
let i;
for (i=0; i<mylength; i++) {
 element = array[i];
}
ready
While
let i = 0;
const mylength = array.length;
while (i++ < mylength) {
 element = array[i];
}
ready
es2015 code for..of
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 el = _step.value;

    element = el;
  }
} catch (err) {
  _didIteratorError = true;
  _iteratorError = err;
} finally {
  try {
    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 Jan Nowotny on