简体   繁体   中英

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?

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

Because NSArray is immutable, the objects are literally internally stored in an array, eg:

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM