Reputation: 154
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 );
}
Upvotes: 0
Views: 107
Reputation: 41374
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.
Upvotes: 0
Reputation: 40649
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.
Upvotes: 0
Reputation: 564
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.
Upvotes: 0
Reputation: 17919
The iterations are made 3 times.
Also, you will call step1(obj) n times, then step2(obj) n times, then step3(obj) n times.
Upvotes: 0
Reputation: 3859
If you are asking about any language, SNIPPET 1 should be faster.
Upvotes: 0
Reputation: 66851
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.
Upvotes: 1