0

I am populating an array with string objects. There can be thousands of these. I am doing a lot of alloc and inits inside a for loop, which I know is expensive. What is the better, more efficient way to do this?

Thanks

 //loop through the array of dictionaries
 for(NSUInteger i =0; i < [latestResults count]; i++){

        self.workingEntry = [[AppRecord alloc] init];

        //Get the next dictionary from the array of dictionaries
        NSDictionary *currentRecord = [latestResults objectAtIndex:i];


        //Set the object
        [self.workingEntry setAppURLString:[currentRecord valueForKeyPath:@"id.label"]];
        [self.workingEntry setAppName:[currentRecord valueForKeyPath:@"im:name.label"]];

        NSArray *imageArray = [currentRecord valueForKeyPath:@"im:image.label"];

        [self.workingEntry setImageURLString:[imageArray objectAtIndex:0]];
        [self.workingEntry setArtist:[currentRecord valueForKeyPath:@"im:artist.label"]];

       //Add object to array
       [self.workingArray addObject:self.workingEntry];

        currentRecord = nil;
        self.workingEntry = nil;
        imageArray = nil;


    }
4
  • 3
    Are you optimizing because you're worried it will be slow, or do you know from observation that it is slow? Have you profiled your code? Commented Sep 14, 2012 at 16:03
  • From past experience of profiling object creation in loops, I just want to avoid creating and tearing down thousands of objects if possible because they are expensive. Commented Sep 14, 2012 at 16:08
  • Are those properties on AppRecord all copy properties? Commented Sep 14, 2012 at 16:14
  • No, they are (nonatomic,strong) Commented Sep 14, 2012 at 16:18

1 Answer 1

2

Off the cuff, I'd be more worried about all those valueForKeyPath: calls than calls to +alloc.

Irrelevant until it is measured, though.

If you want to reduce the # of allocations, move to using singletons or a global cache or some other mechanism to uniquify the objects. Of course, you then run the risk of a performance bottleneck in cache maintenance.

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

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.