I have a question to correct my understanding of the efficiency of accessing vector elements using index access (using the [] operator) or using an iterator.
I understand that an “iterator” is more efficient than “index access”. (I also think vector::end() more efficient than vector::size() ).
Now I have written sample code to measure it (under Windows 7 using Cygwin, with g ++ 4.5.3)
Index access cycle version (previously marked as random access):
int main() { std::vector< size_t > vec ( 10000000 ); size_t value = 0; for( size_t x=0; x<10; ++x ) { for ( size_t idx = 0; idx < vec.size(); ++idx ) { value += vec[idx]; } return value; } }
Iterator loop code:
for (std::vector< size_t >::iterator iter = vec.begin(); iter != vec.end(); ++iter) { value = *iter; }
I am surprised to see that the "index access" version is much faster. I used the time command to measure. The rooms were:
using g++ source.cpp (no optimization) index access
real 800 ms
access to iterator
real 2200ms
Do these numbers make sense? (I repeated runs several times) And I wondered what details I was missing and why I was wrong ...
using g ++ -O2 access index, real time: ~ 200 ms
iterator access, real time: ~ 200 ms
I repeated the tests on different platforms (amd64 w / g ++ and power7 w xlC) and I see that all the time when I used the optimized code, the sample programs have the same runtime.
modify the changed code to add values ( value += *iter ) instead of a simple assignment. Added information about the compiler options. Added new numbers to use -O2. * edit2 changed the header correcting "iterator performance" to "access performance".
c ++ iterator vector stl
Carsten greiner
source share