Reputation: 2906
I have always understood that the data in a NSArray is stored contiguously in the memory of the computer(one object after another). My question is how is a NSSet stored? If each object is stored in different places in the computers memory then surly it will be slower than an array?
Cheers
Do NSSets work more like a linked list?
Upvotes: 2
Views: 773
Reputation: 3522
The implementation of NSArray, NSMutableArray, NSSet, NSMutableSet and other collections changes depending on the number of objects in the collection. You will find more details here and in this more in depth analysis in this blog post.
As @Jean-Denis suggests, you should choose your collection based on their semantics.
Upvotes: 1
Reputation: 5120
Create a NSArray is much faster than create a NSSet. But search for all objects in NSSet is much faster than search for all objects in NSArray, especially you are using indexOfObject:
method to search the NSArray. (You can test it by yourself, 10,000 objects should be enough to show you the difference.)
But when you choosing which should be used, speed is not the most important thing to be considered.
If you want to make sure that one object should be stored ONLY ONCE, use NSSet, otherwise use NSArray, your object will be stored as much times as you insert it. And of course NSArray's objects are ordered.
Upvotes: 2
Reputation: 6852
Whether you use an NSArray
or an NSSet
should not depend on their performance characteristics but the semantics of what you want to represent.
An NSArray
is an ordered collection - with no holes - of items accessed by an index. Duplicates allowed.
An NSSet
is unordered, and cannot store the same object twice.
Without knowing what you want to do, it's difficult to say more.
Upvotes: 2
Reputation: 8638
The storage used by NSArray
is not documented. And you should not assume that it is the same for all arrays. There is an excellent write up at ridiculousfish.com, Our arrays aren’t.
If you are wondering what is the fastest with your requirements. You have to do the tests yourself or be more specific about how you intend to use NSSet
.
Upvotes: 3