-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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