title: node.js response.write(data) taking long time when size of data is small
body: <p>I've noticed a strange behavior of the performance of the following code in node.js. When the size of <code>content</code> is 1.4KB, the response time of the request is roughly 16ms. However, when the size of <code>content</code> is only 988 bytes, the response time of the request is strangely much longer, roughly <strong>200ms</strong>:</p>
  
  <pre><code>response.writeHead(200, {"Content-Type": "application/json"});
  response.write(JSON.stringify(content, null, 0));
  response.end();
  </code></pre>
  
  <p>This does not seem intuitive. Looking into Firebug's net tab, the increase/difference all comes from receiving (waiting on the other hand is 16ms for both).</p>
  
  <p>I've made the following change to fix it so that both cases have 16ms response time:</p>
  
  <pre><code>response.writeHead(200, {"Content-Type": "application/json"});
  response.end(JSON.stringify(content, null, 0));
  </code></pre>
  
  <p>I've looked through node.js <a href="http://nodejs.org/api/http.html#http_response_write_chunk_encoding" rel="noreferrer">doc</a> but so far haven't found related info. My guess this is related to the buffering, but could node.js preempt between <code>write()</code> and <code>end()</code>? </p>
  
  <p><strong>Update:</strong></p>
  
  <p>This was tested on v0.10.1 on Linux.</p>
  
  <p>I tried to peek into <a href="https://github.com/joyent/node/blob/v0.10.1-release/lib/http.js" rel="noreferrer">source</a> and have identified the difference between the 2 path. The first version has 2 Socket.write calls.</p>
  
  <pre><code>writeHead(...)
  write(chunk)
    chunk = Buffer.byteLength(chunk).toString(16) + CRLF + chunk + CRLF;
    ret = this._send(chunk);
      this._writeRaw(chunk);
        this.connection.write(chunk);
  end()
    ret = this._send('0\r\n' + this._trailer + '\r\n'); // Last chunk.
      this._writeRaw(chunk);
        this.connection.write(chunk);
  </code></pre>
  
  <p>The second, good version has just 1 Socket.write call:</p>
  
  <pre><code>writeHead(...)
  end(chunk)
    var l = Buffer.byteLength(chunk).toString(16);
    ret = this.connection.write(this._header + l + CRLF +
                                chunk + '\r\n0\r\n' +
                                this._trailer + '\r\n', encoding);
  </code></pre>
  
  <p>Still not sure what makes the first version not working well with smaller response size.</p>