1

In a book, I see the code:

words = [[NSMutableArray alloc] initWithCapacity:[masterWordList count]];

and let's say [masterWordList count] is 15. And then the code built the array up by using a loop for 10 times:

[words addObject:[masterWordList objectAtIndex:randomNum]];

I wonder why words has to be initWithCapacity... and to 15 slots? Can't it be 10 or 11 (if a nil is needed at the end... and also, won't addObject automatically grow the array size? I tried using init instead of initWithCapacity and the code worked too. So can the code in the book be simplified to just init?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

2 Answers2

4

initWithCapacity: simply gives the class initializer a "hint" as to the eventual size of the array. That way, it can allocate enough space in advance if you know you're going to need it. Using initWithCapacity: can theoretically provide for better performance because it may mean that the array doesn't have to reallocate memory (internally) as you add objects to it (I don't know if it actually does this in the current implementation, but it's possible). As you've guessed, it's only a hint and using initWithCapacity: is entirely optional. Just because you've given initWithCapacity: a certain size doesn't mean your array can't grow to hold more elements than that. Also, calling init instead will work just fine.

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • 1
    Exactly. I'd recommend you use `-init` unless profiling shows that inserting objects is taking a lot of time. (This is not purely theoretical--I have had to use `-initWithCapacity:` for speed reasons... once.) – andyvn22 Apr 15 '12 at 21:07
3

I wonder why words has to be initWithCapacity... and to 15 slots?

In fact, initWithCapacity: is generally not necessary at all. It may or may not reserve space in a useful way. My understanding is that it's something of a historic appendage.

Can't it be 10 or 11 (if a nil is needed at the end...)

It could be 10. As was mentioned on your other question, nil isn't part of the array. It's just a sentinel value for the creating method call itself -- it's not an object and doesn't become a member of the collection.

also, won't addObject: automatically grow the array size?

Yes it will; you can create a mutable array without specifying any starting size and it will grow as needed.

So can the code in the book be simplified just to init?

Yes.

Community
  • 1
  • 1
jscs
  • 63,694
  • 13
  • 151
  • 195
  • thanks for your answer. I accepted Andrew's answer for mentioning that it is a mechanism to provide hint so that the size doesn't have to dynamically grow every single time for performance reason – nonopolarity Apr 16 '12 at 09:14