I have question to correct my understanding of efficiency of accessing elements of a vector by using index access (with operator []) or using an iterator.

My understanding is "iterator" is more efficient than "index access". (also I think vector::end() is more efficient than vector::size()).

Now I wrote sample code measure it (under Windows 7 using Cygwin, with g++ 4.5.3)

The index access loop version (formerly labeled 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;
  }
}

The iterator loop code is this:

    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 quicker. I used the time command to "measure". The numbers were :

results using g++ source.cpp (no optimizations) index access

real 800ms

iterator access

real 2200ms

Do these numbers make sense? (I repeated the runs multiple times) And I wondered what details I miss and why I am mistaken...

results using g++ -O2 index access, time real: ~200ms

iterator access, time real: ~200ms

I repeated tests on different platform (amd64 w/ g++ and power7 w xlC) and see that all the time I used optimized code the example programs have similar execution time.

edit changed code to add values ( value += *iter ) instead of just using assignment. Added details about compiler options. Added new numbers for using -O2. *edit2 changed title correcting "iterator efficiency" to

Edit
Report