BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

day 2 (sets & arrays)

Forums > 100 Days of Swift

why sets are faster than arrays if we search for a specific item ?


Imagine you have a university where there are 1000 Abdallah Yassers walking around. How do you find the one who lives in Building 786, Apartment 60?

You'll have to take a while and look at a lot of ID cards.

But what if you went to an exclusive university where they only admitted ONE Abdallah Yasser.

Then you'll find that student rather quickly.

Sets are guaranteed to have no duplicate items.


what about if there is not duplicate items in array , will sets still faster ?


Taken from SwiftLee

Performance differences Another reason to go for a Set is when performance is important or when a large amount of data is expected. Elements in a Set need to conform to the Hashable protocol which makes Set optimized for performance. It takes the same amount of time to lookup an element in a small collection vs a large collection.


Look into something called time complexity, which is a calculation of how long it takes an algorithm to run. Time complexity is described using what is call Big O notation.

Finding an item in an array has what is called O(n) or linear time complexity, meaning that how long it takes depends on how many items (n) there are in the array. Essentially, to find an item in an array, you have to go through every item until you find the one you want. If it happens to be the first item, then you're in luck but if it happens to be deeper into the array, you gotta go through a bunch more. So, as you might expect, an array with 10 items can be searched much faster than an array with 10,000 items.

Finding an item in a set has O(1) or constant time complexity, meaning that it takes the same amount of time to find an item regardless of how many items there are in the set. So it will take the exact same amount of time to search a set containing 10,000 items as it does to search a set containing 10 items.


@twoStraws has a nice video about using sets.

You may pick up some other pointers about sets in this 5 minutes overview.

HWS explains Sets


Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.