Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

buffer: improve fill(number) performance #31489

Merged
merged 1 commit into from
Jan 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 26 additions & 5 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,12 @@ const {
ObjectCreate,
ObjectDefineProperties,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
ObjectGetPrototypeOf,
ObjectSetPrototypeOf,
SymbolSpecies,
SymbolToPrimitive,
Uint8ArrayPrototype,
} = primordials;

const {
Expand Down Expand Up @@ -101,6 +104,13 @@ const {
addBufferPrototypeMethods
} = require('internal/buffer');

const TypedArrayPrototype = ObjectGetPrototypeOf(Uint8ArrayPrototype);

const TypedArrayProto_byteLength =
ObjectGetOwnPropertyDescriptor(TypedArrayPrototype,
'byteLength').get;
const TypedArrayFill = TypedArrayPrototype.fill;

FastBuffer.prototype.constructor = Buffer;
Buffer.prototype = FastBuffer.prototype;
addBufferPrototypeMethods(Buffer.prototype);
Expand Down Expand Up @@ -1001,11 +1011,22 @@ function _fill(buf, value, offset, end, encoding) {
return buf;
}

const res = bindingFill(buf, value, offset, end, encoding);
if (res < 0) {
if (res === -1)
throw new ERR_INVALID_ARG_VALUE('value', value);
throw new ERR_BUFFER_OUT_OF_BOUNDS();

if (typeof value === 'number') {
// OOB check
const byteLen = TypedArrayProto_byteLength.call(buf);
const fillLength = end - offset;
if (offset > end || fillLength + offset > byteLen)
throw new ERR_BUFFER_OUT_OF_BOUNDS();

TypedArrayFill.call(buf, value, offset, end);
} else {
const res = bindingFill(buf, value, offset, end, encoding);
if (res < 0) {
if (res === -1)
throw new ERR_INVALID_ARG_VALUE('value', value);
throw new ERR_BUFFER_OUT_OF_BOUNDS();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Future enhancement: res < 0 is sometimes a coercion-to-nan, sometimes not because bindingFill() returns either undefined or a number.

Changing Fill() in node_buffer.cc to always return a number is probably beneficial for performance.

}
}

return buf;
Expand Down