Skip to content

Commit

Permalink
[v12.x-backport] stream: avoid unecessary nextTick
Browse files Browse the repository at this point in the history
If we are not going to emit 'close' then there is no reason to
schedule it.

PR-URL: nodejs#29194
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
ronag authored and Stewart Addison committed Jan 24, 2020
1 parent 3203feb commit e1cdc9d
Showing 1 changed file with 9 additions and 25 deletions.
34 changes: 9 additions & 25 deletions lib/internal/streams/destroy.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ function destroy(err, cb) {
}

this._destroy(err || null, (err) => {
const emitClose = (w && w.emitClose) || (r && r.emitClose);
if (err) {
if (w) {
w.errored = true;
Expand All @@ -51,12 +52,14 @@ function destroy(err, cb) {
if (cb) {
// Invoke callback before scheduling emitClose so that callback
// can schedule before.
if (emitClose) {
process.nextTick(emitCloseNT, this);
}
cb(err);
// Don't emit 'error' if passed a callback.
process.nextTick(emitCloseNT, this);
} else if (err) {
process.nextTick(emitErrorCloseNT, this, err);
} else {
process.nextTick(emitClose ? emitErrorCloseNT : emitErrorNT, this, err);
} else if (emitClose) {
process.nextTick(emitCloseNT, this);
}
});
Expand All @@ -65,34 +68,15 @@ function destroy(err, cb) {
}

function emitErrorCloseNT(self, err) {
emitErrorNT(self, err);
emitCloseNT(self);
self.emit('error', err);
self.emit('close');
}

function emitCloseNT(self) {
const r = self._readableState;
const w = self._writableState;

if ((w && w.emitClose) || (r && r.emitClose)) {
self.emit('close');
}
self.emit('close');
}

function emitErrorNT(self, err) {
const r = self._readableState;
const w = self._writableState;

if ((w && w.errorEmitted) || (r && r.errorEmitted)) {
return;
}

if (w) {
w.errorEmitted = true;
}
if (r) {
r.errorEmitted = true;
}

self.emit('error', err);
}

Expand Down

0 comments on commit e1cdc9d

Please sign in to comment.