NSArray containsObject: a faster alternative?

I did a few runs in my iOS app with tools, and I saw that 90% of the main thread load at startup (about 1000 ms) was caused by containsObject: calls. This is on the main topic, and I do not think it is cool.

Is there a faster alternative to this method? Algorithm or other method?

Any suggestions?

ADDITIONAL INFORMATION:

  • I looked at my code again. I realized that I really do not need to know the order of the objects only if the object is part of this set. This means that NSSet will do everything perfectly (and I think it’s faster).

  • Number of objects - in this set there can be 1000+ objects.

+7
source share
2 answers

If you use NEEDS to use an array, skip a little lower


Alternatives

Other options may include:

  • Using NSDictionary , which uses key-> value pairs that (I expect) will have O (1) reading complexity due to the extra key storage space

  • If you do not use duplicates and the order is not important, using NSSet will offer a higher degree of reading (I do not know what complexity will be, documents will probably be)


Using array

If you save the array, you can search in O(log n) time instead of O(n) , since you can use binary search.

Caveat Lector : it was written into memory

 -(void) /*adding*/ { int proposedIndex = 0; proposedIndex = [array indexOfObject:node inSortedRange:NSMakeRange(0, array.count) options:NSBinarySearchingInsertionIndex usingComparator: ^ NSComparisonResult(id obj1, id obj2) { if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending; if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending; else return NSOrderedSame; }]; [array insertObject:node atIndex:proposedIndex]; } -(id) /* Getting */ { int location = [array indexOfObject:node inSortedRange:NSMakeRange(0, array.count) options:NSBinarySearchingFirstEqual usingComparator: ^ NSComparisonResult(id obj1, id obj2) { if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending; if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending; else return NSOrderedSame; }]; if (location == NSNotFound) return nil; return [array objectAtIndex:location]; } 
+11
source

You can use NSSet containsObject faster than NSArray

0
source

All Articles