NSMutableSet addObject

I have a class that wraps around an NSMutableSet object, and I have an instance method that adds objects (using the addObject: method) to the NSMutableSet .

This works well, but I smell the performance because inside the method I explicitly call containsObject: before adding the object to the set.

Three-part question:

  • Do I need to call containsObject: before adding an object to the set?
  • If so, what actual method should I use, containsObject or containsObjectIdenticalTo: :?
  • If this is not the case, then which contains method is called under the hood of addObject: :? This is important to me because if I pass the object to containsObject: it will return true, but if I pass it to containsObjectIdenticalTo: it will return false.
+4
source share
1 answer

If you wrap an NSMutableSet , then the call to containsObject: not needed, since the set ( by definition ) does not contain duplicates. Thus, if you try to insert an object that is already in the set, nothing will happen.

As far as performance is concerned, don't worry about it if you don't rate it as a problem. I would be very very surprised if I could, because the set (at least the smart implementation of the set) has O (1) search time (average case). I guarantee that NSSet and friends are smart implementations. :)

From what I have gathered about the implementation of NSSet , it calls -hash for objects as a way to group them into cells if you use containsObject: or addObject: If you use containsObjectIdenticalTo: it will still use -hash to narrow down the search process, and then (essentially) do pointer comparisons to find an identical object.

+8
source