Size and Volatility NSArray

In Java, I usually initialize arrays of a certain size, and then add and replace objects as my code continues. In Objective-C, I cannot do this using NSArray. The code I ported from Java often needs to use NSMutableArray, which I believe works less efficiently than NSArray. (My best guess about how NSMutableArray stores its members uses a linked list, but I could be wrong)

Are there any types of arrays for Objective-C that have fixed sizes and allow changes to the array? Why is it impossible to replace objects in a specific NSArray object? I can do this with C arrays, why not Objective C?

+1
source share
4 answers

Your guess is wrong, NSMutableArray will not be slower than a regular NSArray .

NSMutableArray will not use a linked list; it will use a dynamic array. It is every bit as fast as a simple array, with the exception of inserts where you need to resize. But as they expand exponentially, they are amortized to almost the same value unless you click on the resize.

It is basically the same as Java ArrayList .

+6
source

In Objective-C, many classes have mutable and immutable variations. For immutable NSArrays, there may be performance or memory benefits, but if you need an array that you can modify, just use NSMutableArray. There is no reason for concern or concern. This is what they are for.

You can initialize mutable arrays with the given capabilities, although you are not forever attached to this capacity - if necessary, the size of the array will increase beyond the capabilities.

 int numberOfItems = ... NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:numberOfItems]; 

Any optimization benefit available to NSArray depends on its immutable nature. Thus, the syntax aside, you cannot realize the advantages of an immutable object when what you need for actual use is changed (for example, you need to replace objects in your case).

+2
source

Do not assume that NSMutableArray too slow for you. Profile, do not speculate.

You can also check out NSPointerArray if you are developing a Mac OS X application. It is not available on iOS.

+2
source

You must use NSMutableArray if you want to replace a specific object. And create an array using

  + (id)arrayWithCapacity:(NSUInteger)numItems 

or

 - (id)initWithCapacity:(NSUInteger)numItems 

of NSMutableArray and specify the size of the array.

+1
source

Source: https://habr.com/ru/post/1395280/


All Articles