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: #15178
Refs: https://jsperf.com/triple-equals-vs-double-equals/3
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Timothy Gu <timothygu99@gmail.com>
  • Loading branch information
apapirovski authored and jasnell committed Sep 20, 2017
1 parent b09eeb4 commit 5e4f87a
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions lib/buffer.js
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 5e4f87a

Please sign in to comment.