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

perf: improve Buffer.from(buf) by 29x #24341

Merged
merged 4 commits into from
Jun 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions ext/node/polyfills/internal/buffer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -229,11 +229,22 @@ function fromArrayLike(array) {
return buf;
}

function fromUint8Array(u8) {
const buf = new Uint8Array(u8.buffer, u8.byteOffset, u8.byteLength);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf.slice();
Comment on lines +233 to +235
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
const buf = new Uint8Array(u8.buffer, u8.byteOffset, u8.byteLength);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf.slice();
const buf = new Uint8Array(u8);
Object.setPrototypeOf(buf, Buffer.prototype);
return buf;

buf.slice refers to Buffer.prototype.slice which has undesired behavior.

$ cat a.mjs
import { Buffer } from "node:buffer";

const buf = new Uint8Array(1);
Buffer.from(buf)[0] = 1;
console.log(buf[0]);
$ node a.mjs
0
$ deno run a.mjs
0
$ ./deno-canary run a.mjs
1

Copy link
Member

Choose a reason for hiding this comment

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

@0f-0b would you be willing to open a PR with that fix?

Copy link
Contributor

Choose a reason for hiding this comment

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

would you be willing to open a PR with that fix?

Opened #24352.

}

function fromObject(obj) {
if (obj.length !== undefined || isAnyArrayBuffer(obj.buffer)) {
if (typeof obj.length !== "number") {
return createBuffer(0);
}

if (obj instanceof Uint8Array) {
return fromUint8Array(obj);
}

return fromArrayLike(obj);
}

Expand Down