gpt4 book ai didi

ios - 使用 arrayWithCapacity 有什么好处

转载 作者:可可西里 更新时间:2023-11-01 03:28:44 26 4
gpt4 key购买 nike

arrayWithCapacity 是在 NSArray.h 中定义并在 NSArray.m

中实现的方法

当我查看 GNUStep 的代码时假设,我可以得到 arrayWithCapacity 是调用 initWithCapacity 的普通方法:

+ (id) arrayWithCapacity: (NSUInteger)numItems
{
return AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()]
initWithCapacity: numItems]);
}

initWithCapacity是一个只做自初始化的简单方法。

- (id) initWithCapacity: (NSUInteger)numItems
{
self = [self init];
return self;
}

与执行的项目数有关的内存分配无关。
使用arrayWithCapacity 方法有什么好处?简单地使用 [[NSArray alloc] init] 会更好吗?

最佳答案

期望提供明确的大小可以改善内存分配,因为在添加项目时无需调整数组的大小。在实践中,它只是一个提示,并且有一些证据表明它并未实际使用(请参阅基础集合类中的 objc.io article)。

关于ios - 使用 arrayWithCapacity 有什么好处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24957911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com