const arr = [];
const ARRAY_SIZE = parseInt(process.argv[2], 10) || 10;
const RUNS = Math.ceil(1000000000 / ARRAY_SIZE);

console.log(`Performing ${RUNS} runs of arrays with ${ARRAY_SIZE} elements`);

for (let i = 0; i < ARRAY_SIZE; i++) arr[i] = i;

function runTest(name, testFunction) {
  if (global.gc) global.gc();
  console.time(name);
  let result;

  for (let r = 0; r < RUNS; r++) {
    result = testFunction();
  }

  console.timeEnd(name);
  console.log(result);
}

for (let repeats = 0; repeats < 3; repeats++) {
  runTest("for", function () {
    let count = 0;
    for (let i = 0, l = arr.length; i < l; i++) {
      count += arr[i];
    }
    return count;
  });

  runTest("forOf", function () {
    let count = 0;
    for (const el of arr) {
      count += el;
    }
    return count;
  });

  runTest("forEach", function () {
    let count = 0;
    arr.forEach((v) => {
      count += v;
    });
    return count;
  });
}