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

Avoid a buffer copy when decoding utf-8 in node 10 #1054

Merged
merged 2 commits into from
Mar 25, 2021

Conversation

jridgewell
Copy link
Contributor

No description provided.

@@ -352,7 +352,7 @@ else if (typeof Buffer !== 'undefined') {

return buffer;
};
decodeUTF8 = bytes => Buffer.from(bytes).toString();
decodeUTF8 = bytes => Buffer.from(bytes.buffer).toString();
Copy link
Owner

Choose a reason for hiding this comment

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

These aren't equivalent:

var array = new Uint8Array([51, 52, 53, 54, 55])
var slice = array.subarray(1, 4)
console.log({
  a: Buffer.from(slice).toString(),
  b: Buffer.from(slice.buffer).toString(),
})

This prints { a: '456', b: '34567' }.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah, I didn't think we called this with anything but a full-view Uint8Array. I can update to use byteOffset and byteLength for decoding.

Copy link
Contributor

Choose a reason for hiding this comment

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

@jridgewell I don't understand why this change will avoid buffer copy, can you give an explanation ?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

See https://nodejs.org/api/buffer.html#buffer_static_method_buffer_from_arraybuffer_byteoffset_length:

This creates a view of the ArrayBuffer without copying the underlying memory. For example, when passed a reference to the .buffer property of a TypedArray instance, the newly created Buffer will share the same allocated memory as the TypedArray's underlying ArrayBuffer.

Passing an ArrayBuffer means the new Buffer instance will be backed by the same memory. Passing an array-like forces a the Buffer to allocate a contiguous memory block, and it then has to iterate over the array to copy the data to the new block.

@evanw evanw merged commit 94846a1 into evanw:master Mar 25, 2021
@jridgewell jridgewell deleted the node-10-decode branch March 25, 2021 08:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants