title: Efficiency of vector index access vs iterator access
body: <p>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.</p>
  
  <p>My understanding is "iterator" is more efficient than "index access".
  (also I think <code>vector::end()</code> is more efficient than <code>vector::size()</code>). </p>
  
  <p>Now I wrote sample code measure it (under Windows 7 using Cygwin, with g++ 4.5.3)</p>
  
  <p>The index access loop version (formerly labeled as random access):</p>
  
  <pre><code>int main()
  {
    std::vector&lt; size_t &gt; vec ( 10000000 );
    size_t value = 0;
  
    for( size_t x=0; x&lt;10; ++x )
    {
      for ( size_t idx = 0; idx &lt; vec.size(); ++idx )
      {
        value += vec[idx];
      }
      return value;
    }
  }
  </code></pre>
  
  <p>The iterator loop code is this:</p>
  
  <pre><code>    for (std::vector&lt; size_t &gt;::iterator iter = vec.begin(); iter != vec.end(); ++iter) {
          value = *iter;
      }
  </code></pre>
  
  <p>I am surprised to see that the "index access" version is much quicker. I used the <code>time</code> command to "measure". The numbers were :</p>
  
  <blockquote>
    <p>results using <code>g++ source.cpp</code>  (no optimizations)
    index access </p>
    
    <p>real 800ms</p>
    
    <p>iterator access</p>
    
    <p>real 2200ms</p>
  </blockquote>
  
  <p>Do these numbers make sense? (I repeated the runs multiple times) And I wondered what details I miss and why I am mistaken... </p>
  
  <blockquote>
    <p>results using g++ -O2
    index access, time real: ~200ms</p>
    
    <p>iterator access, time real: ~200ms</p>
  </blockquote>
  
  <p>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.</p>
  
  <p><strong>edit</strong> changed code to add values ( <code>value += *iter</code> ) instead of just using assignment. Added details about compiler options. Added new numbers for using -O2.
  *<em>edit2</em> changed title correcting "iterator efficiency" to "accesses efficiency". </p>