Skip to content

Commit c2abbd1

Browse files
committed
buffer,util: refactor for performance
internal/util.js defined toInteger() and toLength() but they were only used by buffer.js. Inlining these small functions results in a small but statistically-significant performance gain. PR-URL: #12153 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com> Reviewed-By: Michaël Zasso <targos@protonmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent b09f738 commit c2abbd1

File tree

4 files changed

+8
-87
lines changed

4 files changed

+8
-87
lines changed

lib/buffer.js

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,9 @@ function fromArrayLike(obj) {
216216
}
217217

218218
function fromArrayBuffer(obj, byteOffset, length) {
219-
byteOffset = internalUtil.toInteger(byteOffset);
219+
// convert byteOffset to integer
220+
byteOffset = +byteOffset;
221+
byteOffset = byteOffset ? Math.trunc(byteOffset) : 0;
220222

221223
const maxLength = obj.byteLength - byteOffset;
222224

@@ -226,7 +228,11 @@ function fromArrayBuffer(obj, byteOffset, length) {
226228
if (length === undefined) {
227229
length = maxLength;
228230
} else {
229-
length = internalUtil.toLength(length);
231+
// convert length to non-negative integer
232+
length = +length;
233+
length = length ? Math.trunc(length) : 0;
234+
length = length <= 0 ? 0 : Math.min(length, Number.MAX_SAFE_INTEGER);
235+
230236
if (length > maxLength)
231237
throw new RangeError("'length' is out of bounds");
232238
}

lib/internal/util.js

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -165,21 +165,3 @@ exports.normalizeEncoding = function normalizeEncoding(enc) {
165165
}
166166
}
167167
};
168-
169-
/*
170-
* Implementation of ToInteger as per ECMAScript Specification
171-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger
172-
*/
173-
const toInteger = exports.toInteger = function toInteger(argument) {
174-
const number = +argument;
175-
return Number.isNaN(number) ? 0 : Math.trunc(number);
176-
};
177-
178-
/*
179-
* Implementation of ToLength as per ECMAScript Specification
180-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tolength
181-
*/
182-
exports.toLength = function toLength(argument) {
183-
const len = toInteger(argument);
184-
return len <= 0 ? 0 : Math.min(len, Number.MAX_SAFE_INTEGER);
185-
};

test/parallel/test-internal-util-toInteger.js

Lines changed: 0 additions & 32 deletions
This file was deleted.

test/parallel/test-internal-util-toLength.js

Lines changed: 0 additions & 35 deletions
This file was deleted.

0 commit comments

Comments
 (0)