Skip to content

Commit 5e4f87a

Browse files
apapirovskijasnell
authored andcommitted
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: #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]>
1 parent b09eeb4 commit 5e4f87a

File tree

1 file changed

+3
-3
lines changed

1 file changed

+3
-3
lines changed

lib/buffer.js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,14 @@ Buffer.from = function(value, encodingOrOffset, length) {
175175
if (isAnyArrayBuffer(value))
176176
return fromArrayBuffer(value, encodingOrOffset, length);
177177

178-
if (value == null)
178+
if (value === null || value === undefined)
179179
throw new TypeError(kFromErrorMsg);
180180

181181
if (typeof value === 'number')
182182
throw new TypeError('"value" argument must not be a number');
183183

184184
const valueOf = value.valueOf && value.valueOf();
185-
if (valueOf != null && valueOf !== value)
185+
if (valueOf !== null && valueOf !== undefined && valueOf !== value)
186186
return Buffer.from(valueOf, encodingOrOffset, length);
187187

188188
var b = fromObject(value);
@@ -292,9 +292,9 @@ function allocate(size) {
292292
function fromString(string, encoding) {
293293
var length;
294294
if (typeof encoding !== 'string' || encoding.length === 0) {
295-
encoding = 'utf8';
296295
if (string.length === 0)
297296
return new FastBuffer();
297+
encoding = 'utf8';
298298
length = binding.byteLengthUtf8(string);
299299
} else {
300300
length = byteLength(string, encoding, true);

0 commit comments

Comments
 (0)