NSMutableSet 添加对象
我有一个包装 NSMutableSet 对象的类,并且有一个实例方法,可以将对象(使用 addObject: 方法)添加到 NSMutableSet< /代码>。
这工作得很好,但我感觉到了性能问题,因为在方法中我在将对象添加到集合之前显式调用 containsObject:
。
三部分问题:
- 在将对象添加到集合之前,我是否需要调用
containsObject:
? - 如果是这样,那么我应该使用什么实际方法,
containsObject
或containsObjectIdenticalTo:
? - 如果不是这样,那么在
addObject:
的底层会调用什么contains
方法?这对我来说很重要,因为如果我将一个对象传递给containsObject:
,它将返回 true,但如果我将它传递给containsObjectIdenticalTo:
,它将返回 false。
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:
- Do I need to be calling
containsObject:
before I add an object to the set? - If so, then what actual method should I be using,
containsObject
orcontainsObjectIdenticalTo:
? - If that is not so, what
contains
method gets invoked under the hood ofaddObject:
? This is important to me because if I pass an object tocontainsObject:
it would return true, but if I pass it tocontainsObjectIdenticalTo:
it would return false.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您要包装
NSMutableSet
,则无需调用containsObject:
,因为集合 (根据定义)不包含重复项。因此,如果您尝试插入集合中已有的对象,则不会发生任何事情。就性能影响而言,不要担心它,除非您确实认为它是一个问题。如果你能做到的话,我会非常非常惊讶,因为一个集合(至少是一个集合的智能实现)具有 O(1) 查找时间(平均情况)。我向您保证
NSSet
和朋友都是聪明的实现。 :)根据我收集的有关
NSSet
实现的信息,如果您使用,它会在对象上调用
或-hash
作为将它们“分组”到容器中的一种方式>containsObject:addObject:
。如果您使用containsObjectIdenticalTo:
,它仍然会使用-hash
来缩小搜索过程,然后(本质上)进行指针比较以查找相同的对象。If you're wrapping an
NSMutableSet
, then invokingcontainsObject:
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 usecontainsObject:
oraddObject:
. If you usecontainsObjectIdenticalTo:
, it'll still use-hash
to narrow down the search process, and then (essentially) do pointer comparisons to find the identical object.