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.
  • Loading branch information
Trott committed Apr 1, 2017
1 parent c68da89 commit 5236d8c
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 @@ -142,24 +142,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 5236d8c

Please sign in to comment.