Loop Performance Comparison

Benchmark created on


Setup

// Setup: Initialize an array of 1 million numbers for testing
var items = [];
for (var i = 0; i < 1e6; i++) {
    items.push(i);
}

Test runner

Ready to run.

Testing in
TestOps/sec
mapWithIndex
function mapWithIndex() {
  const result = [];
  for (let i = 0; i < items.length; i++) {
    result.push(items[i] * 2);
  }
  return result;
}
ready
for loop
function forLoop() {
  const result = [];
  for (let i = 0; i < items.length; i++) {
    result.push(items[i] * 2);
  }
  return result;
}
ready
for of loop
function forOfLoop() {
  const result = [];
  for (const item of items) {
    result.push(item * 2);
  }
  return result;
}
ready
forEach loop
function forEachLoop() {
  const result = [];
  items.forEach(function(item) {
    result.push(item * 2);
  });
  return result;
}
ready

Revisions

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