Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing NSMutableArray with and without capacity [duplicate]

Possible Duplicate:
NSMutableArray initWithCapacity nuances
Objective-c NSArray init versus initWithCapacity:0

What is the difference between following line of code? what is the exact advantage and disadvantage? suppose next I will do 3 addObject operation.

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity: 5];
NSMutableArray *array = [[NSMutableArray alloc] init];
like image 705
Nom nom Avatar asked Aug 07 '12 14:08

Nom nom


2 Answers

Functionally both statements are identical.

In the first case, you are giving the run time a hint that you will soon be adding five objects to the array so it can, if it likes, preallocate some space for them. That means that the first five addObject: invocations may be marginally faster using the first statement.

However, there's no guarantee that the run time does anything but ignore the hint. I never use initWithCapacity: myself. If I ever get to a situation where addObject: is a significant performance bottleneck, I might try it to see if things improve.

like image 88
JeremyP Avatar answered Oct 21 '22 05:10

JeremyP


Regularly the difference with object oriented languages and arrays of varying sizes is: the overhead you will get and the page faults at the memory level.

To put this in another way imagine you have an object that requests 5 spaces in memory (just like your first example) and the second object doesn't reserve any space. Therefore when an object needs to be added to the first, there will already be space in memory for it to just fall in, on the other hand the non-allocated-object will first have to request for space on memory then add it to the array. This doesn't sound so bad at this level but when your arrays increase in size this becomes more important.

From Apple's documentation:

arrayWithCapacity:

Creates and returns an NSMutableArray object with enough allocated memory to initially hold a given number of objects. ... The initial capacity of the new array. Return Value A new NSMutableArray object with enough allocated memory to hold numItems objects.

like image 5
El Developer Avatar answered Oct 21 '22 03:10

El Developer