Monday, June 27, 2016

NSArray Vs NSSet


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
For Example :

NSArray *Arr;
NSSet *Nset;

Arr=[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"2",@"1", nil];
Nset=[NSSet setWithObjects:@"1",@"2",@"3",@"3",@"5",@"5", nil];

NSLog(@"%@",Arr);
NSLog(@"%@",Nset);
 NOTE : NSArray is faster than NSSet for simply holding and iterating. As little as 50% faster for constructing and as much as 500% faster for iterating. Lesson: if you only need to iterate contents, don't use an NSSet.
 If you need to test for inclusion, work hard to avoid NSArray. Even if you need both iteration and inclusion testing, you should probably still choose an NSSet. If you need to keep your collection ordered and also test for inclusion, then you should consider keeping two collections (an NSArray and an NSSet), each containing the same objects.
Share:

0 comments:

Post a Comment