Finding unique keys across the list of records (v9)

Revision 9 of this benchmark created on


Setup

const makeKey = () => ('' + (10000 + Math.floor(Math.random() * 90000))); // string 10000-99999
const KEYS = Array.from(new Set(Array(100).fill(0).map(makeKey))).slice(0, 30); // 30 random strings
const getRandomKey = () => KEYS[Math.floor(Math.random() * KEYS.length)];
const makeKeysAmount = () => (5 + Math.round(Math.random() * 10)); // number 5-15
const makeRecordKeys = () => Array(makeKeysAmount()).fill(0).map(() => getRandomKey()); // array of random amount of random keys
const makeRecord = () => makeRecordKeys().reduce((o, k) => {
  o[k] = true;
  return o;
}, {}); // object like `{ 25807: true, 31171: true, 31874: true, 78835: true, 86366: true }`

const input = Array(1000).fill(0).map(() => makeRecord());

Test runner

Ready to run.

Testing in
TestOps/sec
Collect then deduplicate
const keys = [];

input.forEach(o => {
  keys.push(...Object.keys(o))
});

const result = Array.from(new Set(keys));
ready
Double for
const keys = new Set();

for (let i = 0; i < input.length; i++) {
  const itemKeys = Object.keys(input[i]);
  for (let j = 0; j < itemKeys.length; j++) {
    keys.add(itemKeys[j]);
  }
}

const result = Array.from(keys);
ready
Double forEach
const keys = new Set();

input.forEach(o => {
  Object.keys(o).forEach(k => {
    keys.add(k);
  });
});

const result = Array.from(keys);
ready
Union
let keys = new Set();

input.forEach(o => {
  keys = keys.union(new Set(Object.keys(o)));
});

const result = Array.from(keys);
ready
FlatMap to Set
const result = Array.from(
  new Set(input.flatMap(obj => Object.keys(obj)))
);
ready

Revisions

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