From c0e70354dbf7dcc76e69dd1973451eb10a2ebdfe Mon Sep 17 00:00:00 2001 From: isaacs Date: Fri, 26 Jul 2013 17:05:36 -0700 Subject: [PATCH] stream: Short-circuit buffer pushes when flowing When a stream is flowing, and not in the middle of a sync read, and the read buffer currently has a length of 0, we can just emit a 'data' event rather than push it onto the array, emit 'readable', and then automatically call read(). As it happens, this is quite a frequent occurrence! Making this change brings the HTTP benchmarks back into a good place after the removal of the .ondata/.onend socket kludge methods. --- lib/_stream_readable.js | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index fd7577527c3..7515ffbaa1b 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -147,17 +147,24 @@ function readableAddChunk(stream, state, chunk, encoding, addToFront) { if (state.decoder && !addToFront && !encoding) chunk = state.decoder.write(chunk); - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { + if (!addToFront) state.reading = false; - state.buffer.push(chunk); - } - if (state.needReadable) - emitReadable(stream); + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) + state.buffer.unshift(chunk); + else + state.buffer.push(chunk); + + if (state.needReadable) + emitReadable(stream); + } maybeReadMore(stream, state); }