Skip to content

Commit 1e6186e

Browse files
Trottjasnell
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 dc7d9eb commit 1e6186e

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
@@ -254,7 +254,9 @@ function fromArrayLike(obj) {
254254
}
255255

256256
function fromArrayBuffer(obj, byteOffset, length) {
257-
byteOffset = internalUtil.toInteger(byteOffset);
257+
// convert byteOffset to integer
258+
byteOffset = +byteOffset;
259+
byteOffset = byteOffset ? Math.trunc(byteOffset) : 0;
258260

259261
const maxLength = obj.byteLength - byteOffset;
260262

@@ -264,7 +266,11 @@ function fromArrayBuffer(obj, byteOffset, length) {
264266
if (length === undefined) {
265267
length = maxLength;
266268
} else {
267-
length = internalUtil.toLength(length);
269+
// convert length to non-negative integer
270+
length = +length;
271+
length = length ? Math.trunc(length) : 0;
272+
length = length <= 0 ? 0 : Math.min(length, Number.MAX_SAFE_INTEGER);
273+
268274
if (length > maxLength)
269275
throw new RangeError("'length' is out of bounds");
270276
}

lib/internal/util.js

-18
Original file line numberDiff line numberDiff line change
@@ -143,24 +143,6 @@ exports.cachedResult = function cachedResult(fn) {
143143
};
144144
};
145145

146-
/*
147-
* Implementation of ToInteger as per ECMAScript Specification
148-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger
149-
*/
150-
const toInteger = exports.toInteger = function toInteger(argument) {
151-
const number = +argument;
152-
return Number.isNaN(number) ? 0 : Math.trunc(number);
153-
};
154-
155-
/*
156-
* Implementation of ToLength as per ECMAScript Specification
157-
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tolength
158-
*/
159-
exports.toLength = function toLength(argument) {
160-
const len = toInteger(argument);
161-
return len <= 0 ? 0 : Math.min(len, Number.MAX_SAFE_INTEGER);
162-
};
163-
164146
// Useful for Wrapping an ES6 Class with a constructor Function that
165147
// does not require the new keyword. For instance:
166148
// class A { constructor(x) {this.x = x;}}

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)