Set add vs construct

Benchmark created on


Setup

function generateSalesChunk(salesCount) {
  const allKeys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'];

  return Array.from({ length: salesCount }, () => {
    const numKeys = Math.floor(Math.random() * 7) + 2;
    const selectedKeys = allKeys
      .sort(() => Math.random() - 0.5)
      .slice(0, numKeys);
    
    return Object.fromEntries(
      selectedKeys.map(key => {
        const valueType = Math.floor(Math.random() * 4);
        const value = [
          () => Math.floor(Math.random() * 1000),
          () => `value_${Math.random().toString(36).substring(7)}`,
          () => Math.random() > 0.5,
          () => Math.random() * 100
        ][valueType]();
        
        return [key, value];
      })
    );
  });
}


const chunk = generateSalesChunk(500)

Test runner

Ready to run.

Testing in
TestOps/sec
Iterate and add
const allColumns = new Set()
  for (const sale of chunk) {
    for (const key of Object.keys(sale)) {
      allColumns.add(key)
    }
  }
allColumns.add('salesImportId')
ready
flatMap construct
const allColumns = new Set(
  chunk.flatMap(sale => Object.keys(sale)).concat('salesImportId')
);
ready
no inner loop
let allColumns = new Set()
for (const sale of chunk) {
  allColumns = allColumns.union(new Set(Object.keys(sale)))
}
allColumns.add('salesImportId')
ready
Object assign
const allColumnsObj = Object.assign(
  { salesImportId: null },
  ...chunk
);
const allColumns = Object.keys(allColumnsObj);
ready

Revisions

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