1

I often find myself implementing methods that create a bunch of objects in a loop and return them in a non-mutable array. I'd usually write something like this:

- (NSArray *)myObjects {
    NSMutableArray *_temporaryArray = [NSMutableArray array];
    for (id foo in foos) {
        // ... 
        // create `myObject` from the information in `foo`
        // ... 
        [_temporaryArray addObject:myObject];
    }
    return [NSArray arrayWithArray:_temporaryArray];
}

Somehow this pattern doesn't feel very elegant (creating a temporary mutable instance seems to be an overhead). So now I'm looking for better implementations depending on the use case.

What would be the best implementations for these cases:

  1. focus on performance
  2. focus on memory consumption
  3. focus on code brevity.
3
  • This really is a case of premature optimization - use [NSMutableArray copy] to return an immutable collection. Unless you've profiled your application and found this method to be a huge bottleneck, focus on correctness and safety rather than trying to optimize unnecessarily. What is contained in foos? Can you return an array literal containing all of the myObjects? Commented Aug 30, 2013 at 11:58
  • Maybe you are suggesting a 4. case 'focus on correctness and safety'? The number of objects is determined at runtime, so I don't see how I could return an array literal. Commented Aug 30, 2013 at 12:07
  • I'm suggesting a 1. this is premature optimization Commented Aug 30, 2013 at 12:09

2 Answers 2

3

NSMutableArray is a subclass of NSArray, so this will work just fine:

return _temporaryArray;

(I would avoid the _ prefix, however, as that is commonly used to signify instance variables, not auto variables).

This seems to fit your criteria:

  1. focus on performance: no need to make a copy.
  2. focus on memory consumption: no need to make a copy.
  3. focus on code brevity: no need to make a copy.

Note, however, the caller could, in theory, cast your NSArray back to an NSMutableArray and start modifying the object, however there is only so much you should worry about.

Sign up to request clarification or add additional context in comments.

1 Comment

They could also create a mutable copy and add objects to that, either way the OPs method/object doesn't the returned array so it's irrelevant :) +1 as this way avoids the overhead of creating a second array.
0

Just a minor point:

NSMutableArray *temporaryArray = [NSMutableArray alloc] initWithCapacity:[foos count]];

Although the runtime will only take the capacity as an advisory number, rather than creating one exactly that size.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.