From fc1fa4e2c49aa060b97b139ff02b5be8037dba94 Mon Sep 17 00:00:00 2001 From: Anatoli Papirovski Date: Mon, 4 Sep 2017 08:53:43 -0400 Subject: [PATCH] buffer: improve Buffer.from performance 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: https://github.com/nodejs/node/pull/15178 Refs: https://jsperf.com/triple-equals-vs-double-equals/3 Reviewed-By: Ruben Bridgewater Reviewed-By: James M Snell Reviewed-By: Timothy Gu --- lib/buffer.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index ae9ec5fc8e..7a44ca0f26 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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', @@ -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); @@ -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);