Iterators vs loops

Hello,

What do you think about iterators? Is it something provided for completion or not? Say I want to attribute a value to each object in an array (syntax is close enough to ASOC, so I post it in Obj-C):

  • (IBAction) doCalculation: (id)sender {
    id oneObject;
    NSEnumerator* myIterator = [myArray objectEnumerator];

    for (oneObject in myArray){
    [oneObject setValue: forKey:];} // “Traditional” loop

    while(oneObject = [myIterator nextObject]){
    [oneObject setValue: forKey:];} // Iteration
    }

  • Docs say “fast enumeration” – but how much fast? Do you gain speed from 100’000 items?

  • The iterator is released, so you have to invoke a new one at each time;

  • Coding is the same (in line count as in OO approach): in both case you “tell oneObject to set its value to xxx”

So. is there any good reasons to create this iterator instance?

Thank you for your enlightenment.

What you’re calling a “Traditional” loop is in fact fast enumeration. Using an enumerator was how it was done before fast enumeration’s “for x in y”.

For 10.6 and higher a block could be still faster than fast enumeration


    [myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
         [obj setValue: <some value> forKey:<some key>];
    }


Hi Stefan,

Maybe. does it not depend of the code you have to perform with the object? If the enumerateObjectsUsingBlock method itself is, say, 20% faster as fast enumeration (for… in…) will it not be masked by the effective code itself?

Anyway, I find the (for… in…) much more readable – the time I would gain using enumerateObjectsUsingBlock would be lost when I shall be wondering “What the hell does this line mean?” in two years. :slight_smile:

Good question, It depends on how fast and far you will go. Method dispatching plus fast enumeration is the fastest possible way in Obj-C before it gets pure-C (it is C but you’re still able to get objects the Obj-C way.). But how fast is fast enumeration? Still amazingly fast.

Definitely!

That’s a pretty good argument; don’t get hung up on performance until you know you need it. One of the things you will find is that the jump from AS to Objective-C in many cases is all the optimisation you need.