title: Why is std::vector::operator[] 5 to 10 times faster than std::vector::at()?
body: <p>During program optimization, trying to optimize a loop that iterates through a vector, I found the following fact: ::std::vector::at() is EXTREMELY slower than operator[] !</p>
  
  <p><strong>The operator[] is 5 to 10 times faster than at()</strong>, both in release &amp; debug builds (VS2008 x86).</p>
  
  <p>Reading a bit on the web got me to realize that at() has boundary checking. Ok, but, slowing the operation by up to 10 times?!</p>
  
  <p>Is there any reason for that? I mean, boundary checking is a simple number comparison, or am I missing something?<br>
  The question is what is the real reason for this performance hit?<br>
  Further more, <strong>is there any way to make it even faster</strong>?</p>
  
  <p>I'm certainly going to swap all my at() calls with [] in other code parts (in which I already have custom boundary check!).</p>
  
  <p>Proof of concept:</p>
  
  <pre><code>#define _WIN32_WINNT 0x0400
  #define WIN32_LEAN_AND_MEAN
  #include &lt;windows.h&gt;
  
  #include &lt;conio.h&gt;
  
  #include &lt;vector&gt;
  
  #define ELEMENTS_IN_VECTOR  1000000
  
  int main()
  {
      __int64 freq, start, end, diff_Result;
      if(!::QueryPerformanceFrequency((LARGE_INTEGER*)&amp;freq))
          throw "Not supported!";
      freq /= 1000000; // microseconds!
  
      ::std::vector&lt;int&gt; vec;
      vec.reserve(ELEMENTS_IN_VECTOR);
      for(int i = 0; i &lt; ELEMENTS_IN_VECTOR; i++)
          vec.push_back(i);
  
      int xyz = 0;
  
      printf("Press any key to start!");
      _getch();
      printf(" Running speed test..\n");
  
      { // at()
          ::QueryPerformanceCounter((LARGE_INTEGER*)&amp;start);
          for(int i = 0; i &lt; ELEMENTS_IN_VECTOR; i++)
              xyz += vec.at(i);
          ::QueryPerformanceCounter((LARGE_INTEGER*)&amp;end);
          diff_Result = (end - start) / freq;
      }
      printf("Result\t\t: %u\n\n", diff_Result);
  
      printf("Press any key to start!");
      _getch();
      printf(" Running speed test..\n");
  
      { // operator []
          ::QueryPerformanceCounter((LARGE_INTEGER*)&amp;start);
          for(int i = 0; i &lt; ELEMENTS_IN_VECTOR; i++)
              xyz -= vec[i];
          ::QueryPerformanceCounter((LARGE_INTEGER*)&amp;end);
          diff_Result = (end - start) / freq;
      }
  
      printf("Result\t\t: %u\n", diff_Result);
      _getch();
      return xyz;
  }
  </code></pre>
  
  <p>Edit:<br>
  Now the value is being assiged to "xyz", so the compiler will not "wipe" it out.</p>