views:

63

answers:

1

Hi there,

I've got 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'm smelling a performance hitch because inside the method i'm explicitly calling containsObject: before adding the object to the set.

Three part question:

  1. Do I need to be calling containsObject: before I add an object to the set?
  2. If so, then what actual method should I be using, containsObject or containsObjectIdenticalTo:?
  3. If that is not so, what contains method gets invoked under the hood of addObject:? This is important to me because if I pass an object to containsObject: it would return true, but if I pass it to containsObjectIdenticalTo: it would return false.

Thanks for everything, you guys rock!

+4  A: 

If you're wrapping an NSMutableSet, then invoking containsObject: is unnecessary, since a set (by definition) does not contain duplicates. As such, if you attempt to insert an object that is already in the set, nothing will happen.

As far as a performance hit goes, don't worry about it unless you actually measure it being an issue. I'd be very very very surprised if you even could, because a set (at least, a smart implementation of a set) has O(1) lookup time (average case). I guarantee you that NSSet and friends are smart implementations. :)

From what I've gathered about the implementation of NSSet, it's invoking -hash on the objects as a way to "group" them into bins if you use containsObject: or addObject:. If you use containsObjectIdenticalTo:, it'll still use -hash to narrow down the search process, and then (essentially) do pointer comparisons to find the identical object.

Dave DeLong
@Dave, Thanks dude!
Jacob Relkin