From 5e4f87ae658733c9a39207778760aa32a10c2e59 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 ac4f61bf5d0849..5ef207eb780863 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -175,14 +175,14 @@ Buffer.from = function(value, encodingOrOffset, length) { if (isAnyArrayBuffer(value)) return fromArrayBuffer(value, encodingOrOffset, length); - if (value == null) + if (value === null || value === undefined) throw new TypeError(kFromErrorMsg); if (typeof value === 'number') throw new TypeError('"value" argument must not be a number'); 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); @@ -292,9 +292,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 = binding.byteLengthUtf8(string); } else { length = byteLength(string, encoding, true);