title: Garbage collection of a sliced buffer
body: <p>I have TCP based client/server application with server side on Node.js. Because TCP is a stream and I need separate packets I send two-byte length before every packet (common practice I guess). Big packets can come in few chunks (because of MTU and other things) so I need to extract every packet that I can from current buffer and leave the rest for joining with next incoming chunk and parsing again. I've come up with following code:</p>
  
  <pre><code>function parsePackets(data) {
      // join existing buffer contents with new chunk
      var buffer = Buffer.concat([this.buffer, data]);
  
      var start = 0;
      var end = buffer.length;
  
      var packets = [];
  
      while (true) {
          // wait for at least two bytes
          if (end - start &lt; 2) {
              break;
          }
  
          var length = buffer.readUInt16BE(start);
  
          // wait until we can read whole packet
          if (end - start &lt; length) {
              break;
          }
  
          // push packet data as a separate packet
          //var data = new Buffer(length);
          //buffer.copy(data, 0, start, start + length);
          var data = buffer.slice(start, start + length);
          packets.push(data);
  
          start += length;
      }
  
      // drop parsed buffer contents, leaving the rest
      //var newBuffer = new Buffer(buffer.length - start);
      //buffer.copy(newBuffer, 0, start, buffer.length);
      //this.buffer = newBuffer;
      this.buffer = buffer.slice(start, buffer.length);
  
      return packets;
  }
  </code></pre>
  
  <p>My concern is: Will sliced off buffer contents be garbage collected? Also I'm doing <code>concat</code> that returns new buffer (I assume copying contents from provided buffers, which means they can be garbage collected). Or maybe I need to use <code>copy</code> instead of <code>slice</code> (I have an example in commented lines)?</p>
  
  <p>I want performant code without memory leaks, so I dont want to copy data more than I should. But currently it looks like memory usage of my application just grow bigger and bigger (I don't know how to test it for sure and how to check if sliced off contents will be freed sometime).</p>