Skip to content

Commit 4b2477c

Browse files
committed
net: Track state of setKeepAlive and prevent unnecessary system calls
The state of .setKeepAlive() 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.
1 parent d6f1e39 commit 4b2477c

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

lib/net.js

Lines changed: 11 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 kSetKeepAlive = Symbol('kSetKeepAlive');
261261

262262
function Socket(options) {
263263
if (!(this instanceof Socket)) return new Socket(options);
@@ -272,6 +272,7 @@ function Socket(options) {
272272
this._parent = null;
273273
this._host = null;
274274
this[kLastWriteQueueSize] = 0;
275+
this[kSetKeepAlive] = null;
275276
this[kTimeout] = null;
276277
this[kBuffer] = null;
277278
this[kBufferCb] = null;
@@ -501,8 +502,15 @@ Socket.prototype.setKeepAlive = function(setting, msecs) {
501502
return this;
502503
}
503504

504-
if (this._handle.setKeepAlive)
505-
this._handle.setKeepAlive(setting, ~~(msecs / 1000));
505+
const newValue = [setting, ~~(msecs / 1000)];
506+
if (this._handle.setKeepAlive &&
507+
(this[kSetKeepAlive] == null ||
508+
this[kSetKeepAlive][0] !== newValue[0] ||
509+
this[kSetKeepAlive][1] !== newValue[1])
510+
) {
511+
this[kSetKeepAlive] = newValue;
512+
this._handle.setKeepAlive(...newValue);
513+
}
506514

507515
return this;
508516
};

0 commit comments

Comments
 (0)