title: Loop optimisation techniques in C++
body: <p>In order to increase the performance of our applications, we have to consider <strong>loop optimisation techniques</strong> during the development phase.</p>
  
  <p>I'd like to show you some different ways to iterate over a simple <code>std::vector&lt;uint32_t&gt; v</code>:</p>
  
  <ol>
  <li><p><strong>Unoptimized loop with index:</strong></p>
  
  <pre><code>uint64_t sum = 0;
  for (unsigned int i = 0; i &lt; v.size(); i++)
      sum += v[i];
  </code></pre></li>
  <li><p><strong>Unoptimized loop with iterator:</strong></p>
  
  <pre><code>uint64_t sum = 0;
  std::vector&lt;uint32_t&gt;::const_iterator it;
  for (it = v.begin(); it != v.end(); it++)
      sum += *it;
  </code></pre></li>
  <li><p><strong>Cached <code>std::vector::end</code> iterator:</strong></p>
  
  <pre><code>uint64_t sum = 0;
  std::vector&lt;uint32_t&gt;::const_iterator it, end(v.end());
  for (it = v.begin(); it != end; it++)
      sum += *it;
  </code></pre></li>
  <li><p><strong>Pre-increment iterators:</strong></p>
  
  <pre><code>uint64_t sum = 0;
  std::vector&lt;uint32_t&gt;::const_iterator it, end(v.end());
  for (it = v.begin(); it != end; ++it)
      sum += *it;
  </code></pre></li>
  <li><p><strong>Range-based loop:</strong></p>
  
  <pre><code>uint64_t sum = 0;
  for (auto const &amp;x : v)
      sum += x;
  </code></pre></li>
  </ol>
  
  <p>There are also other means to build a loop in C++; for instance by using <code>std::for_each</code>, <code>BOOST_FOREACH</code>, etc...</p>
  
  <p>In your opinion, which is the best approach to increase the performance and why?</p>
  
  <p>Furthermore, in performance-critical applications it could be useful to <strong>unroll the loops</strong>: again, which approach would you suggest?</p>