Objective-c NSArray init 与 initWithCapacity:0
做
[[NSMutableArray alloc] init];
和
[[NSMutableArray alloc] initWithCapacity:0];
编译成完全相同的东西?
如果它们不同,那么在内存和运行时性能方面有何不同,以及哪种形式“更好”?
Do
[[NSMutableArray alloc] init];
and
[[NSMutableArray alloc] initWithCapacity:0];
compile into the exact same thing?
If they differ, then how, and which form is "better" in terms of memory and runtime performance?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,他们的行为不会相同。
init
将创建一个具有一些未知但很可能非零容量的数组 - 无论作者认为对于大多数情况来说都是合理的默认值。initWithCapacity:0
将请求一个绝对没有分配空间的数组。这意味着什么取决于NSMutableArray
实现:它可能不允许容量为 0 且行为与init
完全相同,或者它可能不会立即分配任何内容,而是分配一些数量(与init
相同,可能也可能不是)当您第一次需要它时。哪个性能“更好”完全取决于您期望如何使用该数组。
-init
表示“我对这个数组没有任何期望;我要么对其进行大量添加和删除,要么它可能会非常小。”-initWithCapacity:
表示“在可预见的未来,我预计该数组的元素数量不会超过这么多。”我认为
initWithCapacity:0
唯一合理的地方是,如果您正在创建一个您不希望在相当长的时间内填充任何内容的数组。请注意,标准性能警告适用于此:除非您分析并确定它是问题,否则它可能不是问题。我真的无法想象这两者之间的差异会很大的情况(除了成千上万的 NSMutableArray 对象)。
No, they will not behave identically.
init
will create an array with some unknown but most likely nonzero capacity—whatever the authors decided was a reasonable default for most situations.initWithCapacity:0
will request an array with absolutely no allocated space. What this means is up to theNSMutableArray
implementation: it might not allow a capacity of 0 and behave exactly asinit
, or it might not immediately allocate anything and instead allocate some amount (the same asinit
, possibly, or maybe not) when you first need it.Which will perform "better" completely depends on how you expect to use the array.
-init
says "I have no expectations for this array; I'll either be adding to and removing from it a lot, or it will likely be pretty small."-initWithCapacity:
says "I expect this array to have no more than this many elements for the foreseeable future."About the only place where I would expect
initWithCapacity:0
to be reasonable is if you are creating an array that you don't expect to fill with anything for a fairly long period of time.Note that the standard performance caveat applies here: it's probably not an issue unless you profile and determine that it is. I can't really imagine a situation (except for thousands upon thousands of
NSMutableArray
objects) where the difference between these two will be substantial.