Skip to content

Commit

Permalink
buffer,util: refactor for performance
Browse files Browse the repository at this point in the history
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 <joyeec9h3@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
Trott authored and evanlucas committed May 1, 2017
1 parent 25b851b commit 0c0241f
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 87 deletions.
10 changes: 8 additions & 2 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ function fromArrayLike(obj) {
}

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

const maxLength = obj.byteLength - byteOffset;

Expand All @@ -238,7 +240,11 @@ function fromArrayBuffer(obj, byteOffset, length) {
if (length === undefined) {
length = maxLength;
} else {
length = internalUtil.toLength(length);
// convert length to non-negative integer
length = +length;
length = length ? Math.trunc(length) : 0;
length = length <= 0 ? 0 : Math.min(length, Number.MAX_SAFE_INTEGER);

if (length > maxLength)
throw new RangeError("'length' is out of bounds");
}
Expand Down
18 changes: 0 additions & 18 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,21 +139,3 @@ exports.cachedResult = function cachedResult(fn) {
return result.slice();
};
};

/*
* Implementation of ToInteger as per ECMAScript Specification
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger
*/
const toInteger = exports.toInteger = function toInteger(argument) {
const number = +argument;
return Number.isNaN(number) ? 0 : Math.trunc(number);
};

/*
* Implementation of ToLength as per ECMAScript Specification
* Refer: http://www.ecma-international.org/ecma-262/6.0/#sec-tolength
*/
exports.toLength = function toLength(argument) {
const len = toInteger(argument);
return len <= 0 ? 0 : Math.min(len, Number.MAX_SAFE_INTEGER);
};
32 changes: 0 additions & 32 deletions test/parallel/test-internal-util-toInteger.js

This file was deleted.

35 changes: 0 additions & 35 deletions test/parallel/test-internal-util-toLength.js

This file was deleted.

0 comments on commit 0c0241f

Please sign in to comment.