NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

day 2 (sets & arrays)

Forums > 100 Days of Swift

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

1      

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.

1      

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

1      

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.

2      

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.

2      

@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

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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.