title: c++ std::ostringstream vs std::string::append
body: <p>In all examples that use some kind of buffering I see they use stream instead of string. How is std::ostringstream and &lt;&lt; operator different than using string.append. Which one is faster and which one uses less resourses (memory).</p>
  
  <p>One difference I know is that you can output different types into output stream (like integer) rather than the limited types that string::append accepts.</p>
  
  <p>Here is an example:</p>
  
  <pre><code>std::ostringstream os;
  os &lt;&lt; "Content-Type: " &lt;&lt; contentType &lt;&lt; ";charset=" &lt;&lt; charset &lt;&lt; "\r\n";
  std::string header = os.str();
  </code></pre>
  
  <p>vs</p>
  
  <pre><code>std::string header("Content-Type: ");
  header.append(contentType);
  header.append(";charset=");
  header.append(charset);
  header.append("\r\n");
  </code></pre>
  
  <p>Obviously using stream is shorter, but I think append returns reference to the string so it can be written like this:</p>
  
  <pre><code>std::string header("Content-Type: ");
  header.append(contentType)
    .append(";charset=")
    .append(charset)
    .append("\r\n");
  </code></pre>
  
  <p>And with output stream you can do:</p>
  
  <pre><code>std::string content;
  ...
  os &lt;&lt; "Content-Length: " &lt;&lt; content.length() &lt;&lt; "\r\n";
  </code></pre>
  
  <p>But what about memory usage and speed? Especially when used in a big loop.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>To be more clear the question is: <strong>Which one should I use and why? Is there situations when one is preferred or the other?</strong> For performance and memory ... well I think benchmark is the only way since every implementation could be different.</p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>Well I don't get clear idea what should I use from the answers which means that any of them will do the job, plus vector.  <code>Cubbi</code> did nice benchmark with the addition of Dietmar Kühl that the biggest difference is construction of those objects. If you are looking for an answer you should check that too. I'll wait a bit more for other answers (look previous update) and if I don't get one I think I'll accept Tolga's answer because his suggestion  to use vector is already done before which means vector should be less resource hungry.</p>