Skip to content

Commit 0c0241f

Browse files
Trottevanlucas
authored andcommitted
buffer,util: refactor for performance
internal/util.js definied 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 <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: James M Snell <[email protected]>
1 parent 25b851b commit 0c0241f

File tree

4 files changed

+8
-87
lines changed

4 files changed

+8
-87
lines changed

lib/buffer.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,9 @@ function fromArrayLike(obj) {
228228
}
229229

230230
function fromArrayBuffer(obj, byteOffset, length) {
231-
byteOffset = internalUtil.toInteger(byteOffset);
231+
// convert byteOffset to integer
232+
byteOffset = +byteOffset;
233+
byteOffset = byteOffset ? Math.trunc(byteOffset) : 0;
232234

233235
const maxLength = obj.byteLength - byteOffset;
234236

@@ -238,7 +240,11 @@ function fromArrayBuffer(obj, byteOffset, length) {
238240
if (length === undefined) {
239241
length = maxLength;
240242
} else {
241-
length = internalUtil.toLength(length);
243+
// convert length to non-negative integer
244+
length = +length;
245+
length = length ? Math.trunc(length) : 0;
246+
length = length <= 0 ? 0 : Math.min(length, Number.MAX_SAFE_INTEGER);
247+
242248
if (length > maxLength)
243249
throw new RangeError("'length' is out of bounds");
244250
}

lib/internal/util.js

-18
Original file line numberDiff line numberDiff line change
@@ -139,21 +139,3 @@ exports.cachedResult = function cachedResult(fn) {
139139
return result.slice();
140140
};
141141
};
142-
143-
/*
144-
* Implementation of ToInteger as per ECMAScript Specification
145-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger
146-
*/
147-
const toInteger = exports.toInteger = function toInteger(argument) {
148-
const number = +argument;
149-
return Number.isNaN(number) ? 0 : Math.trunc(number);
150-
};
151-
152-
/*
153-
* Implementation of ToLength as per ECMAScript Specification
154-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tolength
155-
*/
156-
exports.toLength = function toLength(argument) {
157-
const len = toInteger(argument);
158-
return len <= 0 ? 0 : Math.min(len, Number.MAX_SAFE_INTEGER);
159-
};

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

-32
This file was deleted.

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

-35
This file was deleted.

0 commit comments

Comments
 (0)