Skip to content

Instantly share code, notes, and snippets.

@kazuma0129
Last active October 14, 2022 09:54
Show Gist options
  • Save kazuma0129/ede9903ee3b624a8a455efecc570ad15 to your computer and use it in GitHub Desktop.
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
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