Skip to content

Commit ee9e689

Browse files
rustyconoverTrott
authored andcommitted
net: track state of setNoDelay() and prevent unnecessary system calls
The state of .setNoDelay() is now tracked and code will prevent repeated system calls to setsockopt() when the value has already been set to the desired value for the socket. Change and expand the appropriate test. PR-URL: #31543 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Rich Trott <rtrott@gmail.com> Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 3f70d77 commit ee9e689

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

lib/net.js

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ function initSocketHandle(self) {
257257

258258
const kBytesRead = Symbol('kBytesRead');
259259
const kBytesWritten = Symbol('kBytesWritten');
260-
260+
const kSetNoDelay = Symbol('kSetNoDelay');
261261

262262
function Socket(options) {
263263
if (!(this instanceof Socket)) return new Socket(options);
@@ -271,6 +271,7 @@ function Socket(options) {
271271
this[kHandle] = null;
272272
this._parent = null;
273273
this._host = null;
274+
this[kSetNoDelay] = false;
274275
this[kLastWriteQueueSize] = 0;
275276
this[kTimeout] = null;
276277
this[kBuffer] = null;
@@ -488,8 +489,11 @@ Socket.prototype.setNoDelay = function(enable) {
488489
}
489490

490491
// Backwards compatibility: assume true when `enable` is omitted
491-
if (this._handle.setNoDelay)
492-
this._handle.setNoDelay(enable === undefined ? true : !!enable);
492+
const newValue = enable === undefined ? true : !!enable;
493+
if (this._handle.setNoDelay && newValue !== this[kSetNoDelay]) {
494+
this[kSetNoDelay] = newValue;
495+
this._handle.setNoDelay(newValue);
496+
}
493497

494498
return this;
495499
};

test/parallel/test-net-socket-setnodelay.js

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,26 @@ socket.setNoDelay();
2020

2121
socket = new net.Socket({
2222
handle: {
23-
setNoDelay: common.mustCall(genSetNoDelay(true), truthyValues.length)
23+
setNoDelay: common.mustCall(genSetNoDelay(true), 1)
2424
}
2525
});
2626
truthyValues.forEach((testVal) => socket.setNoDelay(testVal));
2727

2828
socket = new net.Socket({
2929
handle: {
30-
setNoDelay: common.mustCall(genSetNoDelay(false), falseyValues.length)
30+
setNoDelay: common.mustNotCall()
3131
}
3232
});
3333
falseyValues.forEach((testVal) => socket.setNoDelay(testVal));
3434

35+
socket = new net.Socket({
36+
handle: {
37+
setNoDelay: common.mustCall(() => {}, 3)
38+
}
39+
});
40+
truthyValues.concat(falseyValues).concat(truthyValues)
41+
.forEach((testVal) => socket.setNoDelay(testVal));
42+
3543
// If a handler doesn't have a setNoDelay function it shouldn't be called.
3644
// In the case below, if it is called an exception will be thrown
3745
socket = new net.Socket({

0 commit comments

Comments
 (0)