Skip to content

Commit

Permalink
buffer: improve Buffer.from performance
Browse files Browse the repository at this point in the history
Using == null in code paths that are expected to mostly receive
objects, arrays or other more complex data types is not
ideal because typecasting these types is very slow. Change
to instead check === null || === undefined. Also move one
variable assignment in fromString after an if condition
that doesn't need it (and returns if truthy).

PR-URL: nodejs#15178
Refs: https://jsperf.com/triple-equals-vs-double-equals/3
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Timothy Gu <[email protected]>
  • Loading branch information
apapirovski authored and addaleax committed Sep 13, 2017
1 parent 54b4088 commit 26b6eee
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ Buffer.from = function from(value, encodingOrOffset, length) {
if (isAnyArrayBuffer(value))
return fromArrayBuffer(value, encodingOrOffset, length);

if (value == null) {
if (value === null || value === undefined) {
throw new errors.TypeError(
'ERR_INVALID_ARG_TYPE',
'first argument',
Expand All @@ -208,7 +208,7 @@ Buffer.from = function from(value, encodingOrOffset, length) {
);

const valueOf = value.valueOf && value.valueOf();
if (valueOf != null && valueOf !== value)
if (valueOf !== null && valueOf !== undefined && valueOf !== value)
return Buffer.from(valueOf, encodingOrOffset, length);

var b = fromObject(value);
Expand Down Expand Up @@ -322,9 +322,9 @@ function allocate(size) {
function fromString(string, encoding) {
var length;
if (typeof encoding !== 'string' || encoding.length === 0) {
encoding = 'utf8';
if (string.length === 0)
return new FastBuffer();
encoding = 'utf8';
length = byteLengthUtf8(string);
} else {
length = byteLength(string, encoding, true);
Expand Down

0 comments on commit 26b6eee

Please sign in to comment.