Loop Performance Comparison (v2)

Revision 2 of this 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(items, mapper) {
  const result = [];
  for (let i = 0; i < items.length; i++) {
    result.push(mapper(items[i], i));
  }
  return result;
}

function test() {
  mapWithIndex(items, function(item, index) {
    return item * 2;
  });
}

test();
ready
for loop
function test() {
  const result = [];
  for (let i = 0; i < items.length; i++) {
    result.push(items[i] * 2);
  }
  return result;
}

test();
ready
for of loop
function test() {
  const result = [];
  for (const item of items) {
    result.push(item * 2);
  }
  return result;
}

test();
ready
forEach loop
function test() {
  const result = [];
  items.forEach(function(item) {
    result.push(item * 2);
  });
  return result;
}

test();
ready

Revisions

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