title: Buffer vs String speed: Why is String faster?
body: <p>I have this project, called <a href="https://github.com/dalssoft/memcached.js" rel="noreferrer">Memcached.Js</a>, which is a port of Memcached server to Node.js.</p>
  
  <p>I've been playing arround with strings and buffers, comparing memory footprint and performance. For memory, there's no question that buffer is the right choice.</p>
  
  <p>But for my surprise the same is not true for performace. Performing string manipulation is faster than using buffer. This is what I tried:</p>
  
  <pre><code>// Option 1: data.toString() - amazing, but it's the best one
  var commandDataStr = mdata.data.toString().substr(startPos, bytes);
  var commandData = new Buffer(commandDataStr);
  
  // Option 2: data.slice().toString() - the same as above... What?
  var commandDataStr = mdata.data.slice(startPos, startPos + bytes).toString();
  var commandData = new Buffer(commandDataStr);
  
  // Option 3: data.slice() - bad
  var commandData = mdata.data.slice(startPos, startPos + bytes);
  
  // Option 4: data.copy() - bad as well
  var commandData = new Buffer(bytes);
  mdata.data.copy(commandData, 0, startPos, startPos + bytes);
  </code></pre>
  
  <p>The complete code is here:
  <a href="https://github.com/dalssoft/memcached.js/blob/master/lib/memcached.ascii.commands.js#L72" rel="noreferrer">https://github.com/dalssoft/memcached.js/blob/master/lib/memcached.ascii.commands.js#L72</a></p>
  
  <p>Testing the code: <code>ruby test/from_clients/perf_test.rb</code></p>
  
  <p>The tests showed that Strings are faster than Buffer. Since it's not what I was expecting, I think I'm probably doing something wrong, but I can't find exactly what it is. </p>
  
  <p>Can anyone help me here?</p>
  
  <p>Tks!</p>