iOS are fast enumeration collection statement executed multiple times?

55 Views Asked by At

Both variants are exactly the same right?

Variant 1:

for(id<MyAwesomeProtocol> obj in [self.instances copy]) {
    ...
}

Variant 2:

NSArray *instancesCopy = [self.instances copy];
for(id<MyAwesomeProtocol> obj in instancesCopy) {
    ...
}

Will the copy method [self.instances copy] in variant 1 called multiple times for each loop?

It will only be executed once at the beginning of the loop right? So this makes code like variant 2 pretty unnecessary? Am I right?

I think I got confused because the condition statement in normal for-loop will be executed on each loop. Instead of writing:

for (NSUInteger i = 0; i < [self.instances count]; i++) {

}

It might be better (in some cases) to cache the count once for performance reasons:

for (NSUInteger i = 0, count = [self.instances count]; i < count; i++) {

}

Does this still hold true for LLVM 6.0 (Xcode 6.0, iOS 8.0)? Or will such code optimized by the compiler?

PS: I'm not really sure how to phrase my stupid question title ;)

0

There are 0 best solutions below