Objective-c NSArray init 与 initWithCapacity:0

发布于 2024-11-08 22:40:06 字数 211 浏览 0 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

寻梦旅人 2024-11-15 22:40:06

不,他们的行为不会相同。 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 the NSMutableArray implementation: it might not allow a capacity of 0 and behave exactly as init, or it might not immediately allocate anything and instead allocate some amount (the same as init, 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文