Performance: Iterating a vector in a loop..



Hi, im having a discussion with a colleague about iterating through a vector in a loop.

my current way is:

vector<MyType>::iterator itLoop;
for (itLoop = vec.begin(); itLoop != vec.end(); itLoop++)
{
	itLoop->DoSomething();
}

But he was saying its slow because .begin() and .end() are called every loop.

I know that the function is called every iteration, but was under the impression that STL is highly optimised in dealing with things like this, so it shouldnt make too much difference.

Can anyone shed any light on this and explain whether or not it really has any speed hits when doing that, or, if it would be better to re-write the code like this (which i feel is less legible).

vector<MyType>::iterator itLoop, itBegin = vec.begin(), itEnd= vec.end();

for (itLoop = itBegin ; itLoop != itEnd; itLoop++)
{
	itLoop->DoSomething();
}

Thanks for any info.
.



Relevant Pages

  • Re: Performance: Iterating a vector in a loop..
    ... im having a discussion with a colleague about iterating through a ... >> vector in a loop. ... Prev by Date: ...
    (microsoft.public.vc.language)
  • Re: Performance: Iterating a vector in a loop..
    ... im having a discussion with a colleague about iterating through a ... >vector in a loop. ... Prev by Date: ...
    (microsoft.public.vc.language)
  • Re: missing values from files
    ... You are saying ... This will loop 14 times, ... If you want to loop over an array use the ... If you want to loop over a range you still should use the iterating ...
    (perl.beginners)
  • Re: lambda closure question
    ... > What I want to do is pre-load functions with arguments by iterating ... setattr(myclass, item, lamdba self: func(self, item)) ... And that's the correct explanation, ... > reference will always get modified as the loop iterates. ...
    (comp.lang.python)
  • Re: Iterate through member variables of a class
    ... I did that because the OP was asking about iterating through member ... variables of a class by using a while loop. ... you can add or remove elements from the array and the ... So it would be better if I declared the int as a size_t instead? ...
    (comp.lang.cpp)

Loading