sooper
sooper

Reputation: 6039

Why does accessing my NSMutableArray become faster once I've added more objects to it?

Something very odd is going on. I populate my array as follows:

self.workingWithItemCollectionArray = [NSMutableArray arrayWithCapacity:self.itemCollectionArray.count];
self.workingWithItemCollectionArray = [[self.itemCollectionArray mutableCopy]autorelease];

It take a mutable copy of the original NSArray and pass it to the NSMutableArray. When accessing the information contained in this array by the click of a UIButton, there is a slight delay in retrieving the information.

But when I then change the original array to add more items, and then pass this onto the mutable array:

NSMutableArray *editedOriginalArray = [NSMutableArray arrayWithArray:self.itemCollectionArray];
[editedOriginalArray addObjectsFromArray:extraObjectsToAdd];
self.itemCollectionArray = [NSArray arrayWithArray:editedOriginalArray];

self.workingWithItemCollectionArray = [NSMutableArray arrayWithCapacity:self.itemCollectionArray.count];
self.workingWithItemCollectionArray = [[self.itemCollectionArray mutableCopy]autorelease];

It is then after this that I am able to press the button and information is accessed instantly (whereas before the button would stay pressed for a very short time).

Any ideas on why this could be?

Upvotes: 0

Views: 699

Answers (1)

Richard J. Ross III
Richard J. Ross III

Reputation: 55563

It has to do with how NSMutableArray is implemented vs NSArray.

Because NSArray is immutable, the objects are literally internally stored in an array, e.g.:

id *objects = malloc(sizeof(id) * count);

However, when you deal with NSMutableArray, you are dealing with instead, a linked list, as NSMutableArray expects many modifications on the array. So, the lookup on a linked list is much longer, because your objects are not stored in a way where there is a set distance in memory between them.

For more information on linked lists, check here.

Upvotes: 1

Related Questions