Re: Performance: Iterating a vector in a loop..




> 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.

I dont think that begin() is required more then once.
But the fact that you only call end() once is logicaly an improvement.

and im not sure if

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

would be faster either. At this point if the vector is very large,
you may want to set up a test to verify these things yourself.





.



Relevant Pages

  • Re: nested "if"
    ... Is it saying: ... It's a while loop. ... For a particular iteration of the loop, $seq and ... *previous* iteration, but the values that will be used in the inner ...
    (perl.beginners)
  • Re: Accessing Array Elements within [if-else]
    ... iteration, so it will still do one loop should exist): ... it IS true since doing exactly one loop means you can do it ... What I was saying before was, your code is exactly equivalent to: ...
    (comp.lang.tcl)
  • Yow! LOOP macros are LOOPY!
    ... By relying entirely on procedure calls to express iteration, ... to but cleaner than C's FOR loop. ... other macros going around at the time other than MacLisp's ... (bind (vi (vector-ref v i))) ...
    (comp.lang.scheme)
  • Re: Polling, Interrupts, DMA, Synchronous, Asynchronous I/O Definitions
    ... the terminology is less useful than it might be. ... though a "message loop" could arguably be claimed to be ... considering in a particular iteration but what is true for _ALL_ ... watching the "polling" version eating up every single CPU cycle ...
    (alt.lang.asm)
  • Re: Histogram of character frequencies
    ... generated object code may simply be a loop in which elements are ... believe any C compiler anywhere would reject it. ... On the first iteration of the loop you test the end of file indicator ...
    (comp.lang.c)