0

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 ;)

Buju
  • 1,546
  • 3
  • 16
  • 27
  • 1
    possible duplicate of [Is this an inefficient way of using fast enumeration?](http://stackoverflow.com/questions/12281461/is-this-an-inefficient-way-of-using-fast-enumeration) – rintaro Oct 20 '14 at 19:21
  • Such cases should be optimized by the compiler, not by the programmer. – Reinhard Männer Oct 20 '14 at 19:53
  • @rintaro thx for point me to the right question. correct keywords didn't really come in mind when i tried to search for it ;) – Buju Oct 20 '14 at 20:59

0 Answers0