From 6ec38013fbc389c414ef5e0eb39d396dad4d4b25 Mon Sep 17 00:00:00 2001 From: tsctx <91457664+tsctx@users.noreply.github.com> Date: Sat, 13 Apr 2024 20:40:53 +0900 Subject: [PATCH] perf(fetch): improve body mixin methods --- benchmarks/fetch/body-arraybuffer.mjs | 24 ++++++++++++++++++++++++ lib/web/fetch/body.js | 2 +- lib/web/fetch/util.js | 5 ++--- 3 files changed, 27 insertions(+), 4 deletions(-) create mode 100644 benchmarks/fetch/body-arraybuffer.mjs diff --git a/benchmarks/fetch/body-arraybuffer.mjs b/benchmarks/fetch/body-arraybuffer.mjs new file mode 100644 index 00000000000..f05e62dc98b --- /dev/null +++ b/benchmarks/fetch/body-arraybuffer.mjs @@ -0,0 +1,24 @@ +import { group, bench, run } from 'mitata' +import { Response } from '../../lib/web/fetch/response.js' + +const settings = { + small: 2 << 8, + middle: 2 << 12, + long: 2 << 16 +} + +for (const [name, length] of Object.entries(settings)) { + const buffer = Buffer.allocUnsafe(length).map(() => (Math.random() * 100) | 0) + group(`${name} (length ${length})`, () => { + bench('Response#arrayBuffer', async () => { + return await new Response(buffer).arrayBuffer() + }) + + // for comparison + bench('Response#text', async () => { + return await new Response(buffer).text() + }) + }) +} + +await run() diff --git a/lib/web/fetch/body.js b/lib/web/fetch/body.js index 26cce5f3e0c..66b3af6de30 100644 --- a/lib/web/fetch/body.js +++ b/lib/web/fetch/body.js @@ -432,7 +432,7 @@ async function consumeBody (object, convertBytesToJSValue, instance) { // 5. If object’s body is null, then run successSteps with an // empty byte sequence. if (object[kState].body == null) { - successSteps(new Uint8Array()) + successSteps(new Uint8Array(0)) return promise.promise } diff --git a/lib/web/fetch/util.js b/lib/web/fetch/util.js index 8c73f909604..b39b0b75827 100644 --- a/lib/web/fetch/util.js +++ b/lib/web/fetch/util.js @@ -1069,8 +1069,7 @@ async function fullyReadBody (body, processBody, processBodyError) { // 5. Read all bytes from reader, given successSteps and errorSteps. try { - const result = await readAllBytes(reader) - successSteps(result) + successSteps(await readAllBytes(reader)) } catch (e) { errorSteps(e) } @@ -1128,7 +1127,7 @@ async function readAllBytes (reader) { if (done) { // 1. Call successSteps with bytes. - return Buffer.concat(bytes, byteLength) + return bytes.length === 1 ? bytes[0] : Buffer.concat(bytes, byteLength) } // 1. If chunk is not a Uint8Array object, call failureSteps