Re: iterator and index
bnonaj wrote:
G wrote:
It occured to me that which of iterator or index is faster in loops.
Then I tried the code below:
//////////////////////////////
#include<vector>
#include<iostream>
using namespace std;
int main()
{
vector<int> vi;
for(int i=0;i!=100000;++i)
vi.push_back(i);
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;
}
//////////////////////////////
I thought this design was not good.It depent on many factors.
The result is not so exact. It showed that the iterator is a little
faster. But I found that "The execute file that I re-built each time
didn't take equal time,and the disparity was obviously."
Could someone tell me the matter with iterator and index?
And whether is "vi.end()" called when each loop happens?
The semantics of the program must be as if vi.end() (or
vi.size(), in the case of the index) is called each time through
the loop. Since they are almost certainly inline functions, the
compiler might well be able to optimize then, however.
And if I change the code of iterator to:
vector<int>::iterator x=vi.end();
for(vector<int>::iterator iter=vi.begin(); iter!=x;
++i)
will it take less time?
Maybe, maybe not. It depends on the implementation of the
library and how the compiler optimizes.
The results you're getting depend on the optimizations the compiler
can make. Modern compilers will optimize the index in the loop and hence
the near identical performance. But if you switch off optimizations then
I'd expect iterators to be quicker.
I wouldn't. An iterator is often a class type, which means that
operations like ++ involve a function call. And many compilers
switch off inlining when optimization is turned off, so you
might get a function call instead of a single machine
instruction.
As the difference when optimized is negligible, use of an
index is considered more readable and easier to debug.
I wouldn't say that. In C++, the "standard" idiom is to use
iterators. Using the standard idiom makes the code more
readable for someone familiar with the language and its idioms.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]