Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
842 views
in Technique[技术] by (71.8m points)

iphone - Objective-c NSArray init versus 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...