Skip to content

Instantly share code, notes, and snippets.

@JulianKnodt
Forked from kapv89/uniques.js
Last active July 8, 2018 06:11
Show Gist options
  • Save JulianKnodt/fb1eb25fb37633063f0c083b1df0da7e to your computer and use it in GitHub Desktop.
Save JulianKnodt/fb1eb25fb37633063f0c083b1df0da7e to your computer and use it in GitHub Desktop.
Perf test on various methods to extract unique elements out of an array of objects
const f = require('faker');
let dup = (a) => a.map((el) => Object.assign({}, el));
// https://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array
const shuffle = (a) => {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
console.time('seed');
let a = Array.from(Array(20000)).map(() => ({
id: f.random.uuid(),
name: f.name.findName(),
about: f.lorem.paragraphs(1),
tags: [f.lorem.word(), f.lorem.word(), f.lorem.word()]
}));
a = shuffle([...a, ...dup(a), ...dup(a)]);
console.timeEnd('seed');
let u = [];
console.time('reduce');
u = a.reduce((acc, el) => acc.find(it => it.id === el.id) ? acc : acc.concat(el), []);
console.timeEnd('reduce');
u = [];
console.time('for-of');
for (let el of a) {
if (!u.find(it => it.id === el.id)) u.push(el);
}
console.timeEnd('for-of');
u = [];
console.time('set');
const s = new Set();
for (let el of a) {
if (!s.has(el.id)) {
u.push(el);
s.add(el.id);
}
}
console.timeEnd('set');
u = [];
console.time('map');
const m = new Map();
for (let el of a) m.set(el.id, el);
u = m.values();
console.timeEnd('map');
console.time('object');
const o = {};
for (let el of a) o[el.id] = el;
u = Object.values(o);
console.timeEnd('object');
// can only check whether the weak set contains the object or not but actually iterate over
console.time('weakSet');
const ws = new WeakSet();
for (let el of a) ws.add(el);
console.timeEnd('weakSet');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment