开发者

memory allocation in obj c

开发者 https://www.devze.com 2023-03-29 23:38 出处:网络
I am new to Objective C. I have a small doubt on memory allocation. If we declare & allocate memory for a NSArray like this:

I am new to Objective C. I have a small doubt on memory allocation.

If we declare & allocate memory for a NSArray like this:

NSArray * arr = [[NSArray alloc]init];

how much开发者_JAVA百科 memory will be allocated for the array arr?


Hmm. If you really meant NSArray, then the array will be empty, no elements will be stored in it, hence only a small amount of memory is needed that would be needed for any Objective C object anyway. (The exact amount of memory is an implementation detail). But an empty NSArray that cannot be modified is not of much use, so I guess you meant NSMutableArray. For NSMutableArray, the array will be empty initially, but it may still allocate some extra memory (and it is very likely that it will) because Objective C expects the array to grow and it's easier to add new elements to the array if there is already some memory allocated on top of what is strictly needed. The exact amount of extra memory allocated is also an implementation detail.

If you want to ensure that your array takes up as little memory as possible, you can use [[NSMutableArray alloc] initWithCapacity:x] where x is the maximum number of elements you intend to put in the array. It will still have zero size but Objective C will assume that you are going to add x elements to it sooner or later hence it allocates a backing store that is enough for x objects.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号