Skip to content

Commit 5236d8c

Browse files
committed
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.
1 parent c68da89 commit 5236d8c

4 files changed

Lines changed: 8 additions & 87 deletions

File tree

‎lib/buffer.js‎

Lines changed: 8 additions & 2 deletions
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‎

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -142,24 +142,6 @@ exports.cachedResult = function cachedResult(fn) {
142142
};
143143
};
144144

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

‎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)