user1467267
user1467267

Reputation:

NSMutableArray removeAllObjects vs new when reusing

Under ARC, would removeAllObjects on a NSMutableArray be more intense for the CPU (releasing the objects individually explicitly) than simply doing myArray = [NSMutableArray new]; and just let ARC catch the whole released memory-block on it's next release round?

I could test this with 2 pieces of code, but due to optimization and such I'm really just curious about the mechanics. From a C perspective it feels like calling all objects to be released sounds more intense, but maybe the dealloc tree in Objective-C might be efficient enough for ARC to do this at an equal speed?

Upvotes: 5

Views: 437

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Some code has to loop through that array inside NSMutableArray, and call release on all its non-nil objects. If there is a difference between what code does it, inside ARC or inside NSMutableArray, it should not be noticeable, because the expensive part is not the loop overhead, it's the actual call of release and potential deallocation following it.

There is a more significant difference, though: when you call removeAllObjects, the array retains its internal storage, so it would not have to grow its internal size the next time you start appending to it. If your usage pattern calls for repeated addition of large number of items to the same array, calling removeAllObjects may save you some allocation/reallocation cycles.

Upvotes: 5

Related Questions