Created
July 7, 2018 16:01
-
-
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
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 {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'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This seems biased because the
reduce
andfor-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, [])
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?