2

I'm new to Objective C (with a C++ background). I'm wondering how much memory actually gets set aside here using arrayWithCapacity. I haven't yet told it what type of object I'm going to put in the array.

For instance, if I'm going to store 200 NSString's with 200 characters each will they be contiguous in memory? And if so, would storing 200 bool values be wasting a lot of memory?

I hope you see where I'm going with this. I'm sure I will find the answer after I've used Objective C a bit more, but this is relevant to a project I'm working on right now. So if anyone can explain it I will be grateful. Thanks!!

1
  • 200 items of whatever cannot waste the memory. Even every item takes 1000 bytes, it would be 0.0002 GB of memory. However, a object reference takes 4 bytes, therefore 200 references 0.0000008 GB. (All units base10.) Commented Jun 10, 2016 at 18:50

1 Answer 1

5

NSArray doesn't store the strings themselves in your example. It stores pointers to the strings. arrayWithCapacity allocates at least enough storage to store those 200 pointers. But that doesn't mean 200*sizeof(pointer) either. NSArray does not promise contiguous storage. It may store its pointers any way it likes, and it can change its mind and reorganize itself at runtime if it likes. So it allocates "enough that it doesn't need to grow before you add 200 objects."

If you want to explore the current details (subject to change) of the underlying data structure, see the CFArray source code. If you want more discussion on the subject of NSArray performance, see Array from fish.

Just to throw another little wrinkle, in some cases strings are short enough that they get encoded directly into the pointer itself. (This is also done for numbers.) See Tagged Pointer Strings by Mike Ash for a nice intro to that. So sometimes the pointer is the whole object and nothing else is allocated.

Basically, many intuitions you bring from C++ don't apply to Cocoa. C++ encourages you to think very carefully about how things are implemented under the covers. Cocoa encourages you to just write to the API and trust that Apple will make it performant for most common use cases on their platforms. If you try to second-guess Apple, you can easily get burned when the underlying implementation changes. (Of course sometimes you have to dig into the details to fix a performance problem; it's just not encouraged at every stage the way it often is in C++.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.