使用 arrayWithCapacity 有什么好处 [英] What is the advantage of using arrayWithCapacity

查看:86
本文介绍了使用 arrayWithCapacity 有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

arrayWithCapacity is a method defined in NSArray.h and implemented in NSArray.m

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

When I look at the code that GNUStep provided, I can get that arrayWithCapacity is a normal method that calls initWithCapacity:

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

initWithCapacity 是一个简单的方法,它只进行自初始化.

And initWithCapacity is a simple method that only does self initialization.

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

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

Nothing about memory allocation with number of items executed.
What is the advantage of using the arrayWithCapacity method? Is it better to simply use [[NSArray alloc] init]?

推荐答案

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

The expectation is that providing an explicit size improves memory allocation as there's no need to adjust the size of the array as items are added. In practice, it is just a hint and there's some evidence that it's not actually used (see this objc.io article on The Foundation Collection Classes).

这篇关于使用 arrayWithCapacity 有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆