title: ostream_iterator vs for each loop efficiency
body: <p>I saw this users <a href="https://stackoverflow.com/questions/50203865/output-vectort-in-template-function">post yesterday</a>. And I thought that was a cool way to output a vector. So I typed up an example and asked myself how does this compare to a <code>for each</code> loop?</p>
  
  <pre><code>template &lt;typename T&gt;
  void printVectorO(std::vector&lt;T&gt; &amp;v)
  {
      std::cout &lt;&lt; "Ostream_iterator contents: " &lt;&lt; std::endl;
      auto start = std::chrono::high_resolution_clock::now();
      std::ostream_iterator&lt;T&gt; ost(std::cout, " ");
      std::copy(begin(v), end(v), ost);
      std::cout &lt;&lt; std::endl;
  
      auto end = std::chrono::high_resolution_clock::now();
      auto time = end - start;
      auto nano = std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(time);
      std::cout &lt;&lt; "Ostream_iterator computation took: " &lt;&lt; nano.count() &lt;&lt; " nano seconds"&lt;&lt; std::endl;
      std::cout &lt;&lt; std::endl;
  }
  
  template &lt;typename T&gt;
  void printVectorC(std::vector&lt;T&gt; &amp;v)
  {
      std::cout &lt;&lt; "For Each Loop contents: " &lt;&lt; std::endl;
      auto start = std::chrono::high_resolution_clock::now();
      for (auto &amp;&amp; e : v) std::cout &lt;&lt; e &lt;&lt; " ";
      std::cout &lt;&lt; std::endl;
  
      auto end = std::chrono::high_resolution_clock::now();
      auto time = end - start;
      auto nano = std::chrono::duration_cast&lt;std::chrono::nanoseconds&gt;(time);
      std::cout &lt;&lt; "For Each Loop took: " &lt;&lt; nano.count() &lt;&lt; " nano seconds" &lt;&lt; std::endl;
      std::cout &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>I used 3 vectors to test this:</p>
  
  <pre><code>std::vector&lt;double&gt; doubles = { 3.15, 2.17, 2.555, 2.014 };
  std::vector&lt;std::string&gt; strings = { "Hi", "how", "are", "you" };
  std::vector&lt;int&gt; ints = { 3, 2 , 2 , 2 };
  </code></pre>
  
  <p>And I get various results. The <code>for each</code> loop always beats the <code>ostream_iterator</code> when I output the doubles (ex 41856 vs 11207 and 55198 vs 10308 nanoseconds). Sometimes the string <code>ostream_iterator</code> beats out the <code>for each</code> loop, and the <code>for each</code> loop and <code>ostream_iterator</code> almost stay neck and neck with integers. </p>
  
  <p>Why is this? What is going on behind the scenes of <code>ostream_iterator</code>? When would I use <code>ostream_iterator</code> over a <code>for each</code> loop when it comes to efficiency and speed? </p>