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 <ruben@bridgewater.de> Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Timothy Gu <timothygu99@gmail.com>
This commit is contained in:
parent
16a81cd2c0
commit
fc1fa4e2c4
@ -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);
|
||||
|
Loading…
x
Reference in New Issue
Block a user