reduce vs. forEach vs. for (v2)

Revision 2 of this benchmark created on


Setup

const input = [
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },  
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
  { a: 1 },
  { b: 2 },
  { c: 3 },
  { d: 4 },
];

Test runner

Ready to run.

Testing in
TestOps/sec
reduce (without mutating the accumulator)
input.reduce((acc, obj) => {
  return { ...acc, ...obj };
}, {});
ready
reduce (with mutating the accumulator)
input.reduce((acc, obj) => {
  Object.assign(acc, obj);
  return acc;
}, {});
ready
forEach
const result = {};
input.forEach(obj => {
  Object.assign(result, obj);
});
ready
for
const result = {};
for (let i = 0; i < input.length; i++) {
  Object.assign(result, input[i]);
}
ready

Revisions

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