Skip to content

Instantly share code, notes, and snippets.

@kapv89
Created July 7, 2018 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kapv89/42e61dde289b0a6da3d742b2e8c43f63 to your computer and use it in GitHub Desktop.
Save kapv89/42e61dde289b0a6da3d742b2e8c43f63 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 {range, shuffle} = require('lodash');
const f = require('faker');
let dup = (a) => a.map((el) => JSON.parse(JSON.stringify(el)));
console.time('seed');
let a = range(0, 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((u, el) => u.map(({id}) => id).indexOf(el.id) > -1 ? u : [...u, el], []);
console.timeEnd('reduce');
u = [];
(() => {
console.time('for-of');
for (let el of a) {
if (u.map(({id}) => id).indexOf(el.id) === -1) {
u.push(el);
}
}
console.timeEnd('for-of');
})();
u = [];
console.time('set');
u = [...new Set(a.map((el) => JSON.stringify(el)))].map((el) => JSON.parse(el));
console.timeEnd('set');
u = [];
(() => {
console.time('map');
let m = new Map();
for (let el of a) {
if (!m.has(el.id)) {
u.push(el);
m.set(el.id, u.length-1);
}
}
console.timeEnd('map');
})();
@JulianKnodt
Copy link

This seems biased because the reduce and for-of both map the entire array every single time.
Instead, you should just use find with a function to concat the array.
In addition, in your reduce [el, ...u] is slow because it must clone u every single time.
Also your variable name shadowing is somewhat confusing.
u = a.reduce((acc, el) => acc.find(it => it.id === el.id) ? acc.concat(el) ? acc, [])

for (let el of a) {
  if (!u.find(it => it.id === el.id)) u.push(el);
}

In addition, your set function is probably a lot slower because of stringify and parse, rather than the set item itself.

Anyways, cool test, I'm curious what it would be like if you just set it on an object?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment