Monday, October 9, 2017

When is it better to use an NSSet over an NSArray?

When the order of the items in the collection is not important, sets offer better performance for finding items in the collection.

The reason is that a set uses hash values to find items (like a dictionary) while an array has to iterate over its entire contents to find a particular object.


The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection.

There are several articles out there that talk about the difference in speed between the two. 

If you're iterating through an unordered collection, NSSet is great. However, in many cases, you need to do things that only an NSArray can do, so you sacrifice the speed for those abilities.

NSSet
  • Primarily access items by comparison
  • Unordered
  • Does not allow duplicates
NSArray
  • Can access items by index
  • Ordered
  • Allows duplicates