Is NSSet faster than NSArray? - ios

i am new to iOS. Anyone know if NSSet are faster than NSArray? Why wouldn't I always just use an NSArray?
Anyone explain me difference between NSSet and NSArray?

NSSet is used to have unique objects.
NSArray may have duplicate objects.
NSSet is an unordered collection.
NSArray is an ordered collection.
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. if you only need to iterate contents, don't use an NSSet.

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.
More detailed information here:
http://www.cocoawithlove.com/2008/08/nsarray-or-nsset-nsdictionary-or.html

When the order of elements isn’t important and performance of testing whether an object is in the set is important. Even though arrays are ordered, testing them for membership is slower than testing sets.

Related

Realm Shuffle RLMArray

How would I go about taking an RLMArray and shuffling it so that the current items in the RLMArray are randomized.
I have looked through the documentation for the RLMArray, however I haven't seen a good way to shuffle it.
Your best bet will probably be to create an NSArray from the RLMArray, shuffle the NSArray (Fisher-Yates is a great algorithm for that), remove all objects from the RLMArray, and add them back in order.

NSArray vs NSDictionary - Which is better for string searching

I am going to store a list of values in a plist and retrieve them. The list will be searched for a value (which may change each time) each time the search method is called. There will probably be about 10 values in the list.
Is either NSArray or NSDictionary better for a search?
I think that NSArray is more appropriate because right now, at least, I don't have a key-value pair data set, just a list.
Could someone confirm and perhaps offer the best method for search the array?
Thanks
The problem is conceptual:
If you have a list of value, you mustn't use NSDictionary. The appropriate data structure is NSArray or NSSet.
Basically, NSSet is faster than NSArray, because doesn't have to consider the order etc.
So if you need just to search a value and the order doesn't matter, the best data structure to use is NSSet (or NSMutableSet if you need it mutable).
Dictionaries will be faster for searching than arrays because the keys are hashed. With an array the system has to check all the items until it finds a match.
The docs for NSSet say that sets are faster in testing for membership than arrays. If you don't have values to store for each key, the best option might be to store the data to your plist as an array. At runtime, read the array, and load it's contents into a set using the NSSet class method setWithArray:
If your data sets are large (many thousands of items) I would suggest doing performance testing with dictionaries where all the values are NSNull against an NSSet. (With a dictionary you'd use objectForKey: and with a set you'd use the containsObject: method
Ignoring timing the best option would be to use an NSArray. NSArray has all sorts of useful methods such as
(NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate
and
(NSIndexSet *)indexesOfObjectsPassingTest:(BOOL (^)(id obj, NSUInteger idx, BOOL *stop))predicate
that you can use for searching within an array.

Get the opposite of intersection between array A and array B

quick question. I have two NSMutableArray:
Array 1: [A,B,C,D,E,F];
Array 2: [B,E,F];
Note that Array 2 is always subset of Array 1 - meaning objects that exist is Array 2, definitely exist is Array 1 as well.
So what I want is to build an array that contain the objects that are NOT in Array 2. Like so
Array 3: [A,C,D];
I've tried using relative complement as outlined in this post but the resulting array is basically the same as Array 1. It doesn't eliminate the objects that exist in Array 2.
I also tried the answer here as well, but still not getting what I want. Unless i'm really doing something very obviously wrong.
Using NSPredicate is much preferable, I guess. But I'm open to ideas and hints.
Note: Just for context, i'm doing this to update my UITableView, basically for data filtering purposes.
Thanks!
UPDATE
So all the answers given so far actually works with simple set of dummy data for me. But when I tested with my real data, the Array 3 that are created is still the same as the Array 1. So, I'm going to give more info about my stuff.
Both arrays are NSMutablArray that store dictionary objects. I'm actually using Parse.com, so the objects in both arrays are PFObject (which is just NSObject, if I'm not mistaken). I don't know how does this affect anything, but yeah, seems to not be working.
Here is a screenshot from the console when I try to step through the process.
Thanks for the help so far guys.
There's no need to go down the predicate route here, you know explicitly what you want to do, and can be expressed with simple, native APIs.
NSMutableArray *mArray3 = [NSMutableArray arrayWithArray:array1];
[mArray3 removeObjectsInArray:array2];
NSArray* array3 = [mArray3 copy];
An important thing to note:
removeObjectsInArray:
This method assumes that all elements in otherArray respond to hash and isEqual:.
For an object to be deemed equal, they need to response to hash and isEqual:, and for those values to match between two equal objects. A good article regarding equality can be read here.
If PFObject simply inherits from NSObject, then the equality checking will be very basic. It will simply check for equality by asking "Are these objects the same object, based on location in memory?". This probably explains why your dummy data works, but the real data does not.
You'll need to subclass PFObject to make it aware of the contents. This means you can override hash and isEqual: to provide a more reasonable statement of equality. For example, "Are these objects the same object, based on the value of the 'name' property". It's up to you to define what makes objects equal.
WDUK's answer is probably the way to go since it's simpler and requires only one new object (plus a copy of that). However, if you like discrete math, NSMutableSet allows you to perform set operations. That is, another (overly complicated, however, very descriptive) answer to your question is:
// convert arrays to sets.
// since array2 is always a subset of array1, we don't need to create a union set.
NSMutableSet *set1 = [NSMutableSet setWithArray:array1];
NSSet *set2 = [NSSet setWithArray:array2];
// find intersecting objects
NSMutableSet *intersection = [NSMutableSet setWithSet:set1];
[intersection intersectSet:set2];
// remove intersecting objects (result: your desired set)
[set1 minusSet:intersection];
NSArray *nonIntersectingObjects = [set1 allObjects];
As WDUK suggests, your problem is easily solved with an NSMutableArray. However, when similar, but more complex, problems arise, set operations might provide an simpler and more elegant solution.
If you want to do it using a predicate here's the way to do it:
NSArray* array1= #[#'A',#'B',#'C',#'D',#'E',#'F'];
NSArray* array2= #[#'B',#'E',#'F'];
NSPredicate* predicate= [NSPredicate predicateWithFormat: #"not(self in %#)",array2];
NSArray* array3=[array1 filteredArrayUsingPredicate: predicate];
SELF represents the evaluated object in the array. The IN operator can be used to check if any object is inside a collection, here is some reference: Predicate programming guide / aggregate operations

What is the most efficient way to find a subarray of elements in array in Objective-C?

I have an array (NSArray or NSMutableArray doesn't matter): SpecID of specific files IDs (109234, etc.). And I have a large array of all files IDs : FilesID.
I need to check whether FilesID contains all the elements of SpecID.
So the question what is the fastest and most efficient way of doing this except simple comparing all the elements to each other in a loop. May be there are some standard method or efficient algorithm?
You could use sets:
NSSet *specIDs = [NSSet setWithArray:specIDarray];
NSSet *fileIDs = [NSSet setWithArray:fileIDarray];
if ([specIDs isSubsetOfSet:fileIDs])
{
// Your file IDs contains every ID found in specIDarray
}
For this to work efficiently, the objects should ideally be NSNumber objects, or if they are custom objects, they should override both hash and isEqual:. The efficiency of sets depends mostly on having a good hash. The Foundation classes, e.g. NSNumber, NSString etc have good hashes.
Also, if you can, load your IDs directly into sets rather than converting them from arrays as this will be slightly more efficient, but otherwise the above is probably as simple as it would get. There may be specialised algorithms which would perform better but only explore those options if the above is too slow.

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?
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]
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 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.
NSOrderedSet is available in iOS 5+ so with that the main difference becomes whether you want duplicate objects in the data structure.
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
An array is used to access items by their index. Any item can be inserted into the array multiple times. Arrays mantain the order of their elements.
A set is used basically only to check if the item is in the collection or not. The items have no concept of order or indexing. You cannot have an item in a set twice.
If an array wants to check if it contains an element, it has to check all its items. Sets are designed to use faster algorithms.
You can imagine a set like a dictionary without values.
Note that array and set are not the only data structures. There are other, e.g. Queue, Stack, Heap, Fibonacci's Heap. I would recommend reading a book about algorithms and data structures.
See wikipedia for more information.
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);
the array
2015-12-04 11:05:40.935 [598:15730] ( 1, 2, 3, 4, 2, 1 )
the set
2015-12-04 11:05:43.362 [598:15730] { ( 3, 1, 2, 5 )}
The main differences have already been given in other answers.
I'd just like to note that because of the way sets and dictionaries are implemented (i.e. using hashes),one should be careful not to use mutable objects for the keys.
If a key is mutated then the hash will (probably) change too, pointing to a different index/bucket in the hash table. The original value won't be deleted and will actually be taken into account when enumerating or asking the structure for its size/count.
This can lead to some really hard to locate bugs.
Here you can find a pretty thorough comparison of the NSArray and NSSet datastructures.
Short conclusions:
Yes, 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.
Of course, 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.
NSDictionary is slower to construct than NSMapTable — since it needs to copy the key data. It makes up for this by being faster to lookup. Of course, the two have different capabilities so most of the time, this determination should be made on other factors.
You would typically use a Set when access speed is of the essence and order doesn’t matter, or is determined by other means (through a predicate or sort descriptor). Core Data for example uses sets when managed objects are accessed via a to-many relationship
Just to add a bit of it i use set sometimes just to remove duplicates from array like :-
NSMutableSet *set=[[NSMutableSet alloc]initWithArray:duplicateValueArray]; // will remove all the duplicate values

Resources