A Little Bit of Background:
When attempting multiple algorithms at Flatiron school I found myself not being able to finish. From this, I wanted to find out why. So I peeked at the solution and found that they were using Set instead of an Array. This led me to questioning what is a Set? How is it different from an Array? And does Set have any bigger advantages over an Array? With a some research I was able to find my answers and teach it to others.
What is a Set?
A Set is a collection of values that a programmer can iterate through similar to an object.
How is a Set different from an Array?
A Set is similar to an array or an object in that you can iterate through one and that it holds a collection of values. However, the main takeaway is that a Set is only able to hold unique values. This means that a value that appears in Set can only appear one time.
Does Set have any bigger advantages
As mentioned previously, Set is not able to have any duplicating values so if a programmer would like to push a new value in an Array they are able to do so as many times as they would like. Through my research into this topic, it was found that adding values to an array is 4 times than adding them to a Set. Iterating through an Array is also much faster than a Set. However, where Set shines is when a programmer would like to remove a value from their collection. If a programmer needed a way to make a unique collection of values Set is much more useful. Set removes the overhead from an Array. When checking an Array with a unique object it goes through checking if that value exists and if it does skip or push, going through every index. The tests that were run were with 10k and 100k elements. With 10k elements an array took 16.7ms and a Set took 20.7ms. However, at 100k elements the array took 1974.8ms and the Set took 83.6ms. Showing the massive disparity between the two. Another test was run that uses 10k elements in an collection and the programmer adds 15 new values and 5 of the are duplicates. The results are an array took 74ms and the Set took 9ms which is a big margin.
In Conclusion
Sets are faster than arrays when dealing with duplicates and checking if any duplicate exists with large amounts of Data. However, Arrays are much faster in all other circumstances. I believe understanding these differences can enhance junior developers.
Here is the link to a Stack Overflow that tested Set vs Array.
Top comments (0)