When is it better to use an NSSet over an NSArray?
I have used NSSets many times in my apps, but I have never created one myself.
When is it better to use an NSSet
as opposed to an NSArray
and why?
Solution 1:
The image from Apple's Documentation describes it very well:
Array
is an ordered (order is maintained when you add) sequence of elements
[array addObject:@1];
[array addObject:@2];
[array addObject:@3];
[array addObject:@4];
[array addObject:@6];
[array addObject:@4];
[array addObject:@1];
[array addObject:@2];
[1, 2, 3, 4, 6, 4, 1, 2]
Set
is a distinct (no duplicates), unordered list of elements
[set addObject:@1];
[set addObject:@2];
[set addObject:@3];
[set addObject:@4];
[set addObject:@6];
[set addObject:@4];
[set addObject:@1];
[set addObject:@2];
[1, 2, 6, 4, 3]
Solution 2:
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.
Solution 3:
The best answer is to this is Apple's own documentation.
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, like this one. 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
That's all there really is to it! Let me know if that helps.
Solution 4:
NSOrderedSet is available in iOS 5+ so with that the main difference becomes whether you want duplicate objects in the data structure.
Solution 5:
NSArray:
- Ordered collection of data
- Allows duplicates
- It is collection type object
NSSet:
- Unordered collection of data
- Does not allow duplicates
- It is also collection type object