For vs forEach vs reduce

Benchmark created on


Setup

const arr = [];

for (let i = 0; i < 100_000; i++) {
  arr.push(i);
}

Test runner

Ready to run.

Testing in
TestOps/sec
One reduce loop
let sum2 = 0

const sum = arr.reduce((s, v) => {
  sum2 += v - 1;
  return s + v;
}, 0);
ready
One reduce one forEach loop
let sum2 = 0

const sum = arr.reduce((s, v) => s + v, 0);

arr.forEach((v) => (sum2 += v - 1));
ready
One for loop
let sum = 0;
let sum2 = 0;

for (let i = 0; i < arr.length; i++) {
  sum2 += arr[i] - 1;
  sum += arr[i];
}
ready
Two for loops
let sum = 0;
let sum2 = 0;

for (let i = 0; i < arr.length; i++) {
  sum2 += arr[i] - 1;
}

for (let i = 0; i < arr.length; i++) {
  sum += arr[i];
}
ready
One forEach
let sum = 0;
let sum2 = 0;

arr.forEach((v) => {
  sum2 += v - 1;
  sum += v;
});
ready
Two forEach
let sum = 0;
let sum2 = 0;

arr.forEach((v) => {
  sum2 += v - 1;
});

arr.forEach((v) => {
  sum += v;
});
ready
While
let sum = 0;
let sum2 = 0;

let i = 0

while(i < arr.length) {
  sum2 += arr[i] - 1;
  sum += arr[i];
  ++i;
}
ready
For...of
let sum = 0;
let sum2 = 0;

for (const v of arr) {
  sum2 += v - 1;
  sum += v;
}
ready

Revisions

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