Faster Codes With Javascript Sets

JavaScript’s Sets can make your code faster — especially as it scales. There is a significant amount of crossover between what an array can do and what a Set can do. But using Sets will often bring runtime benefits that are impossible to achieve with arrays. In this article, we’ll explore how.

The most fundamental difference is that arrays are an indexed collection. That means the value of data in an array is ordered by the index.

const arr = [A, B, C, D];

console.log(arr.indexOf(A)); // Result: 0
console.log(arr.indexOf(C)); // Result: 2

By contrast, Sets are a keyed collection. Instead of using indices, Sets order their data using keys. A Set’s elements are iterable in the order of insertion, and it cannot contain any duplicate data. In other words, every item in a Set must be unique.

Benefits

In a direct comparison, Sets have several advantages over arrays, especially when it comes to a faster run-time:

#Search for an Item: Using indexOf() or includes() to check whether an item exists in an array is slow.

#Deleting an Item: In a Set, you can delete an item by its value. In an array, the equivalent is using splice() based on an element’s index. As in the previous point, depending on indices is slow.

#Insert an Item: It is faster to add an item to a Set than to add an item to an array using push() , unshift() or an equivalent method.

#Storing NaN: You cannot use indexOf() or includes() to find the value NaN , while a Set is able to store this value.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s