views:

17

answers:

2

I have an NSMutableArray that I display through a table view. The problem is that when I add objects to this array, I don't want to have duplicates.

If I create an NSMutableSet from the NSMutableArray, then add objects to the NSMutableSet and then convert it back to an NSMutableArray, is that any more efficient than checking the NSMutableArray through a loop for duplicates before adding an item?

+3  A: 

Generally yes, it would be more efficient to use a set. Constructing a set of n items is O(n log n). Finding all the duplicates in an array by just looping through it will be O(n^2). (If you're really determined you could get O(n log n), but you'd have to kinda rewrite what set already does.)

JoshD
But how are duplicates found in a set? Is a loop used internally?
awakeFromNib
Set are represented internally as binary search trees. To add an item, it finds the appropriate place by traversing the tree (a O(log n) operation.) If it already exists, nothing is inserted (no object created), otherwise it inserts it.
JoshD
My original data source is not a set though. It's an array because it's being displayed in a table view. There will be some overhead in converting the array to a set before insertion. Then the set has to be converted back to an array for display. Is this still efficient?
awakeFromNib
Possibly. There is certainly some overhead, so if your array is really small it won't be a benefit. If it's fairly big, though it would be better. The best way to find out is to try both and compare! :) If you're only adding a few items at a time, it's probably faster to just check the array.
JoshD
+1  A: 

Hi

you can check if the object your adding exists by using

- (NSUInteger)indexOfObject:(id)anObject

if the object exists in the array it will give you an index else it returns

NSNotFound

so you can do an if before adding elements to your array.

i think that its a little better in memory wise because you don't create to objects.

Hope this helps

mklfarha
This would end up being O(n^2) to create the Array of n items. It's an option, but it's not much more efficient than looping through the Array.
JoshD
yes i agree that making a set is more efficient but, he needs a NSMutableArray as a result and making a set then creating a NSMutableArray from it, consumes more memory since you have to make to objects.
mklfarha