Reduce vs Map vs For

Benchmark created on


Setup

const items = [];


for (let i = 0; i < 1_000; i++) {
	items.push({
		id: i,
		type: 'user-id-as-flag'
	})
}

Test runner

Ready to run.

Testing in WebKit 537.36 / undefined
TestOps/sec
Reduce (if includes)
items.reduce((result, item) => {
  if (!['user-id-as-flag'].includes(item.type)) {
    return result;
  }

  return {
    ...result,
    [item.id]: item,
  };
}, {});
ready
Map (if includes)
Object.fromEntries(
  items
    .map((item) => {
      if (!['user-id-as-flag'].includes(item.type)) {
        return null;
      }

      return [item.id, item];
    })
    .filter((item) => !!item)
);
ready
For (if includes)
const result = {};

for (const item of items) {
  if (!['user-id-as-flag'].includes(item.type)) {
    continue;
  }

  result[item.id] = item;
}
ready
Reduce (if equals)
items.reduce((result, item) => {
  if (item.type !== 'user-id-as-flag') {
    return result;
  }

  return {
    ...result,
    [item.id]: item,
  };
}, {});
ready
Map (if equals)
Object.fromEntries(
  items
    .map((item) => {
      if (item.type !== 'user-id-as-flag') {
        return null;
      }

      return [item.id, item];
    })
    .filter((item) => !!item)
);
ready
For (if equals)
const result = {};

for (const item of items) {
  if (item.type !== 'user-id-as-flag') {
    continue;
  }

  result[item.id] = item;
}
ready

Revisions

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