javascript / intermediate
Snippet
Performance Optimization with Set
The Set object is a collection of unique values. Using a Set for lookups is significantly faster than using an array (O(1) vs O(n) complexity) and it provides an elegant way to remove duplicates from an array.
snippet.js
1
2
3
4
5
6
7
8
9
10
const userIds = [10, 20, 30, 10, 40, 20];const uniqueIds = new Set(userIds);// Efficient existence checkif (uniqueIds.has(30)) {console.log('User 30 exists');}// Convert back to Arrayconst dedupedArray = [...uniqueIds];
Breakdown
1
new Set(userIds)
Creates a new Set from the array, which automatically discards any duplicate primitive values.
2
uniqueIds.has(30)
Checks for existence with constant time complexity, regardless of how many elements are in the Set.