To understand how to make code faster using sets, we must first understand the scenarios in which sets must be used instead of arrays −
Since Sets only contain unique elements, it is easier if we know in advance we want to avoid saving duplicate data to our structure.
Basic operations of Set like union(), intersect(), difference(), etc… are easily implemented effectively based on the native built-in operations provided. Due to the delete() method, it makes intersect/union between 2 Sets much more comfortable than doing the same to 2 Arrays. This also makes code faster as random deletes in sets are O(1) while the same in arrays are O(n).
Arrays are meant for ordered and index based access or any action required direct index access to elements (for example, Binary Search). Sets are meant for checking and validating membership of objects in collections.
Search heavy scenarios should use sets. For example, you have authorization and authentication where you check for membership of people in different groups.
Places where order is important and duplicate data is needed should use arrays. For example, sorted collection of objects.
Note −Sets are different than Arrays. They're not meant to replace Arrays, but to provide additional support.