Last active
October 14, 2022 09:54
-
-
Save kazuma0129/ede9903ee3b624a8a455efecc570ad15 to your computer and use it in GitHub Desktop.
Investigate whether there is a difference in calculation speed between "Array" and "Set" for array intersections in javascript
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 intersectionSet = (a, b) => { | |
const setB = new Set(b); | |
return Array.from(new Set([...new Set(a)].filter((x) => setB.has(x)))); | |
}; | |
const intersectionArr = (a, b) => a.filter((x) => b.includes(x)); | |
const genTestArr = () => | |
[...Array(1000000)].map(() => Math.floor(Math.random() * 1000)); | |
// [...Array(1000000)].map(() => `${Math.floor(Math.random() * 1000)}`); | |
const a = genTestArr(); | |
const b = genTestArr(); | |
console.log({ a, b }); | |
console.time("set"); | |
intersectionSet(a, b); | |
console.timeEnd("set"); | |
console.time("arr"); | |
intersectionArr(a, b); | |
console.timeEnd("arr"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment