ForEach vs Reduce

Benchmark created on


Setup

function generateArray(size) {
  const array = [];
  for (let i = 1; i <= size; i++) {
    array.push({
      id: i.toString(),
      properties: {
        useVariableName: Math.random() > 0.5,
        variableName: `var${i}`,
        name: `name${i}`
      }
    });
  }
  return array;
}

let a = generateArray(1000);

let b = {
  '1': 'value1',
  'var2': 'value2',
  'var3': 'value3',
  '3': 'value3',
  '100': 'value100',
};

let updatedB = {};

Test runner

Ready to run.

Testing in
TestOps/sec
ForEach
a.forEach(item => {
  const key = item.properties.useVariableName ? item.properties.variableName : item.id;
  updatedB[item.properties.name] = b[key];
  if (!item.properties.useVariableName) {
    delete updatedB[item.id];
  }
});
ready
Reduce
const updatedB = a.reduce((acc, item) => {
  const key = item.properties.useVariableName ? item.properties.variableName : item.id;
  acc[item.properties.name] = b[key];
  return acc;
}, {});
ready
For loop
for (let i = 0; i < a.length; i++) {
  const item = a[i];
  const key = item.properties.useVariableName ? item.properties.variableName : item.id;
  updatedB[item.properties.name] = b[key];
  if (!item.properties.useVariableName) {
    delete updatedB[item.id];
  }
}
ready

Revisions

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