Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast enumeration?

I am currently developing a game and need really fast enumeration of arrays. I need to run the code 30 times per second and now want to ask what's the best way to accomplish the task. I want to enumerate an array and modify it at the same time.

I know 2 at the moment:

NSMutableArray*array;

int i=0;

int x=0;
 for (myclass*spr in [[array copy] autorelease]) {
    if ([spr isInBounds]) {
        //do something
    } else {
        [array removeObjectAtIndex:x];
        x--;
    }

    x++;
}

and

int x=0;

while(x<[array count])
{
    if(![(myclass*)spr isInBounds]) {
        [array removeObjectAtIndex:x];
        x--;
    }
    x++;
}

What is the fastest way to do this? Do you know other ways? Thanks for your help!

like image 927
user610246 Avatar asked Dec 18 '25 10:12

user610246


1 Answers

In your particular case, the best way is probably to save off the indexes of objects you don't care about in an NSIndexSet and use them after the loop to remove all the objects at once.

NSMutableIndexSet *is = [NSMutableIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(myclass *spr, NSUInteger idx, BOOL *stop) {
    if ([spr isInBounds]) {
        // do something
    } else {
        [is addIndex:idx];
    }
}];
[array removeObjectsAtIndexes:is];
like image 190
Lily Ballard Avatar answered Dec 20 '25 03:12

Lily Ballard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!