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 jasnell committed Apr 4, 2017
1 parent dc7d9eb commit 1e6186e
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 @@ -254,7 +254,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 @@ -264,7 +266,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 @@ -143,24 +143,6 @@ exports.cachedResult = function cachedResult(fn) {
};
};

/*
* 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);
};

// Useful for Wrapping an ES6 Class with a constructor Function that
// does not require the new keyword. For instance:
// class A { constructor(x) {this.x = x;}}
Expand Down
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 1e6186e

Please sign in to comment.