summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorud2 <sjx233@qq.com>2024-06-27 05:11:56 +0800
committerGitHub <noreply@github.com>2024-06-26 17:11:56 -0400
commit86e0292733d6d08bf338b68fd50863aef17b1e44 (patch)
treef042f733aba42f01bf3942f1545b711b0b4dc5d9
parent77ba0019e73710e1e685a8051b9cca79cc6e5054 (diff)
perf(ext/node): improve `Buffer.from(buffer)` (#24352)
Benchmark code from #24341. ```shellsession $ deno run --allow-hrtime bench.mjs 6479.111583 $ target/release/deno run --allow-hrtime bench.mjs 962.753875 $ node bench.mjs 855.174875 ```
-rw-r--r--ext/node/polyfills/internal/buffer.mjs10
-rw-r--r--tests/unit_node/buffer_test.ts11
2 files changed, 11 insertions, 10 deletions
diff --git a/ext/node/polyfills/internal/buffer.mjs b/ext/node/polyfills/internal/buffer.mjs
index a051965a3..c32494555 100644
--- a/ext/node/polyfills/internal/buffer.mjs
+++ b/ext/node/polyfills/internal/buffer.mjs
@@ -220,12 +220,9 @@ function fromString(string, encoding) {
return buf;
}
-function fromArrayLike(array) {
- const length = array.length < 0 ? 0 : checked(array.length) | 0;
- const buf = createBuffer(length);
- for (let i = 0; i < length; i += 1) {
- buf[i] = array[i] & 255;
- }
+function fromArrayLike(obj) {
+ const buf = new Uint8Array(obj);
+ Object.setPrototypeOf(buf, Buffer.prototype);
return buf;
}
@@ -234,6 +231,7 @@ function fromObject(obj) {
if (typeof obj.length !== "number") {
return createBuffer(0);
}
+
return fromArrayLike(obj);
}
diff --git a/tests/unit_node/buffer_test.ts b/tests/unit_node/buffer_test.ts
index 0005b1b5d..07f5dd2c1 100644
--- a/tests/unit_node/buffer_test.ts
+++ b/tests/unit_node/buffer_test.ts
@@ -534,15 +534,18 @@ Deno.test({
});
Deno.test({
- name: "[node/buffer] Buffer from another buffer creates a Buffer",
+ name: "[node/buffer] Buffer from another buffer creates a copy",
fn() {
- const buffer: Buffer = Buffer.from(Buffer.from("test"));
- assertEquals(buffer.length, 4, "Buffer length should be 4");
+ const buffer1: Buffer = Buffer.from("test");
+ const buffer2: Buffer = Buffer.from(buffer1);
+ assertEquals(buffer2.length, 4, "Buffer length should be 4");
assertEquals(
- buffer.toString(),
+ buffer2.toString(),
"test",
"Buffer to string should recover the string",
);
+ buffer1[0] = 114;
+ assertEquals(buffer2.toString(), "test", "Buffer should be a copy");
},
});