n00neimp0rtant
n00neimp0rtant

Reputation: 915

Efficiency + safety: declare new NSArray var, or overwrite existing NSMutableArray with mutableCopy?

I need to sort a mutable array, but in this specific case when it comes time to sort, I don't need it to be mutable anymore. The sortedArrayUsingSelector: method returns an NSArray * even when called by an NSMutableArray * object. I have 3 options:

1) I can make a mutableCopy of the returned NSArray * and store it in the var I already have

NSMutableArray *mutableArray = [NSMutableArray array];

// add a bunch of stuff to the array

mutableArray = [[mutableArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] mutableCopy];

2) I can make a new NSArray * var to hold the returned NSArray *

NSMutableArray *mutableArray = [NSMutableArray array];

// add a bunch of stuff to the array

NSArray *array = [mutableArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

3) I can ignore Xcode's warnings and store the returned NSArray * object in an NSMutableArray * var

NSMutableArray *mutableArray = [NSMutableArray array];

// add a bunch of stuff to the array

mutableArray = [mutableArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

I realize that for most cases the difference is negligible, but considering available resources, efficiency, and safety, which would be the overall "best" option?

EDIT: I hadn't considered that the best option might be to create a non-mutable array from the mutable one before sorting it. Not sure if this would be, in fact, the best option, but something I figured I'd mention.

Upvotes: 2

Views: 236

Answers (2)

Leehro
Leehro

Reputation: 561

The array you get back from sortedArrayUsingSelector won't be a deep copy - it will contain the same pointers as the original array, just in a different order. These array methods in foundation will be well optimized, so I wouldn't worry about it too much.

Instead, just decide what you want. If you want a sorted NSArray * that won't look like an NSMutableArray *, just use sortedArrayUsingSelector, which returns an NSArray *

If you don't need the original unsorted array anymore, just sort the mutable array, like @Gavin suggests.

Upvotes: 0

Gavin
Gavin

Reputation: 8200

Since you have a mutable array already, just use the following method on NSMutableArray:

- (void)sortUsingSelector:(SEL)comparator

That way you're not recreating anything. This is likely more efficient than creating a new, sorted array from the original and then creating a mutable copy of that. Part of the point of having a mutable array in the first place is that you can change stuff around without needing to recreate it each time, so sorting is a very obvious thing to have here.

Upvotes: 1

Related Questions