Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: avoid tick in writable hot path #49966

Merged
merged 1 commit into from
Oct 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 19 additions & 9 deletions lib/internal/streams/writable.js
Original file line number Diff line number Diff line change
Expand Up @@ -612,24 +612,31 @@ function onwrite(stream, er) {
}

if (sync) {
const needDrain = state.length === 0 && (state.state & kNeedDrain) !== 0;
const needTick = needDrain || (state.state & kDestroyed !== 0) || cb !== nop;

// It is a common case that the callback passed to .write() is always
// the same. In that case, we do not schedule a new nextTick(), but
// rather just increase a counter, to improve performance and avoid
// memory allocations.
if (cb === nop) {
if ((state.state & kAfterWritePending) === 0) {
if ((state.state & kAfterWritePending) === 0 && needTick) {
process.nextTick(afterWrite, stream, state, 1, cb);
state.state |= kAfterWritePending;
} else {
state.pendingcb -= 1;
state.pendingcb--;
finishMaybe(stream, state, true);
}
} else if (state.afterWriteTickInfo !== null &&
state.afterWriteTickInfo.cb === cb) {
state.afterWriteTickInfo.count++;
} else if ((state.state & kAfterWriteTickInfo) !== 0 &&
state[kAfterWriteTickInfoValue].cb === cb) {
state[kAfterWriteTickInfoValue].count++;
} else if (needTick) {
state[kAfterWriteTickInfoValue] = { count: 1, cb, stream, state };
process.nextTick(afterWriteTick, state[kAfterWriteTickInfoValue]);
state.state |= (kAfterWritePending | kAfterWriteTickInfo);
} else {
state.afterWriteTickInfo = { count: 1, cb, stream, state };
process.nextTick(afterWriteTick, state.afterWriteTickInfo);
state.state |= kAfterWritePending;
state.pendingcb--;
finishMaybe(stream, state, true);
}
} else {
afterWrite(stream, state, 1, cb);
Expand All @@ -638,7 +645,8 @@ function onwrite(stream, er) {
}

function afterWriteTick({ stream, state, count, cb }) {
state.afterWriteTickInfo = null;
ronag marked this conversation as resolved.
Show resolved Hide resolved
state.state &= ~kAfterWriteTickInfo;
state[kAfterWriteTickInfoValue] = null;
return afterWrite(stream, state, count, cb);
}

Expand Down Expand Up @@ -795,6 +803,8 @@ Writable.prototype.end = function(chunk, encoding, cb) {
if (typeof cb === 'function') {
if (err) {
process.nextTick(cb, err);
} else if ((state.state & kErrored) !== 0) {
process.nextTick(cb, state[kErroredValue]);
} else if ((state.state & kFinished) !== 0) {
process.nextTick(cb, null);
} else {
Expand Down