Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to make your code faster using JavaScript Sets?
While writing code, we always try to make our code easier to read, less complex, more efficient, and smaller in size. For that, we follow several methodologies which make our code efficient. In this article, we shall focus on some techniques based on JavaScript Sets to perform certain array-like or collection-based applications which will run faster and the code will also be concise.
How Sets Differ from Arrays
Arrays are indexed collections where each element is associated with a specific index. On the other hand, Sets are keyed collections where data elements are ordered based on their key values. Sets do not allow duplications, so all elements in the Set are unique.
Benefits of Using Sets Over Arrays
Faster lookups: To check whether an element is present inside an array, we use
indexOf()orincludes()functions. These are slow operations compared to thehas()function in Sets.Efficient deletion: We can delete elements from Sets using their values. In arrays, we use
splice()based on an element's index, which is a slower process.Faster insertion: Inserting elements using
push()orunshift()methods in arrays is slower than Set'sadd()operation.NaN support: Sets can store NaN values, unlike arrays where NaN handling is problematic.
Automatic duplicate removal: Since Sets don't allow duplicate elements, we can remove duplicates by converting an array to a Set and back to an array.
Why Sets Are Faster
Most operations on JavaScript arrays (insert, delete, search) are linear-time operations requiring O(n) time, where n is the array size. Since Sets use hash-based storage, most operations take constant time O(1), making Set performance independent of collection size.
Performance Comparison Examples
Let's create performance tests with 1,000,000 elements to demonstrate the speed difference:
Initial Setup
let A = [];
let S = new Set();
const size = 1000000;
for (let i = 0; i < size; i++) {
A.push(i);
S.add(i);
}
console.log("Array size:", A.length);
console.log("Set size:", S.size);
Array size: 1000000 Set size: 1000000
Performance Test: Item Search
const toSearch = 56420;
console.time('ArraySearch');
let arrayResult = A.indexOf(toSearch) !== -1;
console.timeEnd('ArraySearch');
console.time('SetSearch');
let setResult = S.has(toSearch);
console.timeEnd('SetSearch');
console.log("Array found:", arrayResult);
console.log("Set found:", setResult);
ArraySearch: 0.172ms SetSearch: 0.008ms Array found: true Set found: true
Performance Test: Item Insertion
console.time('ArrayInsert');
A.push(size);
console.timeEnd('ArrayInsert');
console.time('SetInsert');
S.add(size);
console.timeEnd('SetInsert');
ArrayInsert: 0.140ms SetInsert: 0.009ms
Performance Test: Item Deletion
function deleteFromArray(array, element) {
let idx = array.indexOf(element);
return idx !== -1 && array.splice(idx, 1);
}
const toDelete = 56420;
console.time('ArrayDelete');
let arrayDelResult = deleteFromArray(A, toDelete);
console.timeEnd('ArrayDelete');
console.time('SetDelete');
let setDelResult = S.delete(toDelete);
console.timeEnd('SetDelete');
console.log("Array deletion result:", arrayDelResult);
console.log("Set deletion result:", setDelResult);
ArrayDelete: 1.090ms SetDelete: 0.008ms Array deletion result: [56420] Set deletion result: true
Practical Use Case: Removing Duplicates
const arrayWithDuplicates = [1, 2, 2, 3, 3, 4, 5, 5];
console.time('RemoveDuplicates');
const uniqueArray = [...new Set(arrayWithDuplicates)];
console.timeEnd('RemoveDuplicates');
console.log("Original:", arrayWithDuplicates);
console.log("Unique:", uniqueArray);
RemoveDuplicates: 0.012ms Original: [1, 2, 2, 3, 3, 4, 5, 5] Unique: [1, 2, 3, 4, 5]
Performance Comparison Table
| Operation | Array Time Complexity | Set Time Complexity | Performance Gain |
|---|---|---|---|
| Search | O(n) | O(1) | ~21x faster |
| Insertion | O(1) | O(1) | ~15x faster |
| Deletion | O(n) | O(1) | ~136x faster |
When to Use Sets
Use Sets when you need:
- Unique values only
- Frequent lookups or membership tests
- Fast insertion and deletion operations
- To remove duplicates from arrays
- Mathematical set operations (union, intersection)
Conclusion
JavaScript Sets provide significant performance improvements over arrays for search, insertion, and deletion operations. With O(1) time complexity for most operations compared to arrays' O(n), Sets are ideal for scenarios requiring frequent lookups and unique value storage. Choose Sets when performance and uniqueness matter more than indexed access.
