views:

72

answers:

6

Is there a difference in the runtime of the following two snippets?

SNIPPET 1:

for ( Object obj : collection ) {
    step1( obj );
    step2( obj );
    step3( obj );
}

SNIPPET 2:

for ( Object obj : collection ) {
    step1( obj );
}

for ( Object obj : collection ) {
    step2( obj );
}

for ( Object obj : collection ) {
    step3( obj );
}
+1  A: 

Of course. The first snippet iterates through the collection only once while the second snippet does it 3 separate times. The second snippet also violates the DRY principle.

ryeguy
Intuitively it would seem you're right but I don't see a difference in runtime performance.Each snippet executes 3N steps, where N is the size of the collection.Some languages have overhead associated with iteration but if we ignore that, I don't see a huge difference betweem the two.
Well if you ignore the iteration difference, what other difference would there be? They're the same then.
ryeguy
+1 for DRY ... plus, if it's a mutable collection (or some object that implements Iterable but isn't really a collection), you might get different operations on each object
kdgregory
obviously i would never write code like this.but my question is more abstract.currently i have each step iterating over the collection anew.these steps are independent. if i refactor to look like snippet 1, i lose readability (the steps have no reason to be in the same loop or method). am i really suffering a performance degredation with snippet 2? i don't think so.
A: 

If you are asking about any language, SNIPPET 1 should be faster.

Marco Mustapic
A: 

The iterations are made 3 times.

Also, you will call step1(obj) n times, then step2(obj) n times, then step3(obj) n times.

Samuel Carrijo
A: 

If one of your method calls will throw an exception, lets say step1 in the middle of the iteration then the second version will stop earlier than the first one. But if step3 throws an exception for the first element then the first version is faster. So the two versions are not equivalent semantically.

Gábor Hargitai
A: 

Is there any difference? Of course.

Is there a difference that matters? It all depends.

If StepN() takes a few nanoseconds, then yes. Otherwise, probably not.

Mike Dunlavey
A: 

Are you asking specifically about performance?

In that case, the answer depends on how fast the collection's iterator is: if Next() is an expensive operation for that particular iterator, then you pay that cost N times in the first version and 3N times in the latter. This is insignificant if your collection is a vector, but more serious when your collection is, say, an interface to some slow file I/O operation.

Crashworks