From 594bb9d558904eef6c7a51bf3450ef33e7ef220b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Mon, 20 Feb 2023 02:25:54 +0100 Subject: [PATCH] os: improve network interface performance This reduces the overhead of getCIDR() to a minimum. No array is allocated anymore and parts are directly sliced out of the netmask string instead. Signed-off-by: Ruben Bridgewater PR-URL: https://github.com/nodejs/node/pull/46598 Reviewed-By: Antoine du Hamel Reviewed-By: James M Snell --- lib/os.js | 33 +++++++++++++++++++++------------ 1 file changed, 21 insertions(+), 12 deletions(-) diff --git a/lib/os.js b/lib/os.js index 055710f5620ee2..0049a9af820eb2 100644 --- a/lib/os.js +++ b/lib/os.js @@ -28,7 +28,6 @@ const { ObjectDefineProperties, StringPrototypeEndsWith, StringPrototypeSlice, - StringPrototypeSplit, SymbolToPrimitive, } = primordials; @@ -225,6 +224,7 @@ function getCIDR(address, netmask, family) { let range = 10; let groupLength = 8; let hasZeros = false; + let lastPos = 0; if (family === 'IPv6') { split = ':'; @@ -232,21 +232,30 @@ function getCIDR(address, netmask, family) { groupLength = 16; } - const parts = StringPrototypeSplit(netmask, split); - for (let i = 0; i < parts.length; i++) { - if (parts[i] !== '') { - const binary = NumberParseInt(parts[i], range); - const tmp = countBinaryOnes(binary); - ones += tmp; + for (let i = 0; i < netmask.length; i++) { + if (netmask[i] !== split) { + if (i + 1 < netmask.length) { + continue; + } + i++; + } + const part = StringPrototypeSlice(netmask, lastPos, i); + lastPos = i + 1; + if (part !== '') { if (hasZeros) { - if (tmp !== 0) { + if (part !== '0') { return null; } - } else if (tmp !== groupLength) { - if ((binary & 1) !== 0) { - return null; + } else { + const binary = NumberParseInt(part, range); + const binaryOnes = countBinaryOnes(binary); + ones += binaryOnes; + if (binaryOnes !== groupLength) { + if ((binary & 1) !== 0) { + return null; + } + hasZeros = true; } - hasZeros = true; } } }