forof vs iterator while

Benchmark created on


Setup

const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function* source(array) {
	for (let i = 0; i < array.length; i++) {
		yield array[i];
	}
}

// Function 1: for...of loop
function forOfLoop(arr) {
  let sum = 0;
  for (const num of arr) {
    sum += num;
  }
  return sum;
}

// Function 2: while loop using [Symbol.iterator]
function whileLoopIterator(arr) {
  let sum = 0;
  const iterator = arr[Symbol.iterator]();
  let result = iterator.next();
  while (!result.done) {
    sum += result.value;
    result = iterator.next();
  }
  return sum;
}

function arrayFromFor(gen) {
	const arr = Array.from(gen);
	let sum = 0;
	for (let i = 0; i<arr.length; i++) {
		sum += arr[i];
	}
	return sum;
}

Test runner

Ready to run.

Testing in
TestOps/sec
for of
forOfLoop(source(array));
ready
while
whileLoopIterator(source(array))
ready
arrayFromFor
arrayFromFor(source(array))
ready

Revisions

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