Re: iterator and index
{ This article might seem to be environment-specific, but the points
raised might be of wider relevance than the quoted source (Intel) might
imply. Hence, approved via "when in doubt, approve"-policy. However,
please keep follow-ups generally relevant to standard C++. -mod/aps }
James Kanze wrote:
Mirek Fidler wrote:
G wrote:
for(size_t i=0;i!=vi.size();++i) //for(vector<int>::iterator
iter=vi.begin();iter!=vi.end();++i)
cout<<vi[i]<<endl; // cout<<*iter<<endl;
}
vector<int>::iterator x=vi.end();
for(vector<int>::iterator iter=vi.begin(); iter!=x;
++i)
will it take less time?
[]
To be more specific, implementation usually uses begin/end pointers and
size has to be computed as (end - begin) / sizeof(T).
A good optimizer will almost certainly rewrite the loop to use a
stepped index, incrementing in fact sizeof(T) each time through
the loop, and comparing with (end - begin). Depending on the
contents of the loop, the compiler might even be able to figure
out that end and begin don't change, and generate exactly the
same code for both loops.
Off hand, what I'd typically expect is:
-- no or very little optimization: the loop with the index is
faster (because no function call for incrementing),
-- very good optimization: both loops generate exactly the same
code, and
-- medium optimization: the iterator version is probably
faster, because it can maintain the pointers (hidden in the
iterators) in registers. (To do this with the indexed
version, the compiler must determine that the pointers in
the vector object never change. Which typically requires
more analysis, since the vector object is typically visible
over a larger scope than the iterator.)
Some more loop optimization hints from IA-32 Intel Architecture
Optimization Reference Manual:
Enable Vectorization
* Use the smallest possible data type. This enables more parallelism
with the use of a longer vector.
* Arrange the nesting of loops so the innermost nesting level is free
of inter-iteration dependencies. It is especially important to avoid
the case where the store of data in an earlier iteration happens
lexically after the load of that data in a future iteration
(called lexically-backward dependence).
* Avoid the use of conditionals.
* Keep induction (loop) variable expressions simple.
* Avoid using pointers, try to replace pointers with arrays and indices.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]