Created
June 1, 2025 04:42
-
-
Save aquapi/294bffc7ae56287dcac0f2a8ba4dfbcd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { summary, run, bench, do_not_optimize } from "mitata"; | |
import { LimitedBytesTransformStream } from "@std/streams"; | |
const register = (name: string, fn: (list: Request[]) => any) => | |
bench(name, function* () { | |
yield { | |
[0]: () => reqs.map((t) => t.clone()), | |
bench: fn, | |
}; | |
}); | |
const reqs = new Array(1000).fill(0).map( | |
(_, i) => | |
new Request("http://localhost", { | |
method: "POST", | |
body: new Blob([ | |
"{", | |
...new Array(Math.floor(10 + i / 20)) | |
.fill(0) | |
.map(() => '"' + crypto.randomUUID() + '":0,'), | |
'"_":"a"}', | |
]), | |
}), | |
); | |
// Example benchmark | |
summary(() => { | |
register("req.json", async (list) => { | |
for (let i = 0; i < list.length; i++) do_not_optimize(await list[i].json()); | |
}); | |
register("parse req.text", async (list) => { | |
for (let i = 0; i < list.length; i++) | |
do_not_optimize(JSON.parse(await list[i].text())); | |
}); | |
}); | |
summary(() => { | |
const LIMIT = 300; | |
const decoder = new TextDecoder(); | |
register("manual stream", async (list) => { | |
for (let i = 0; i < list.length; i++) { | |
const stream = list[i].body; | |
if (stream != null) { | |
try { | |
let remainingBytes = LIMIT; | |
let chunks = ""; | |
for ( | |
let reader = stream.getReader(), data = await reader.read(); | |
!data.done; | |
data = await reader.read() | |
) { | |
remainingBytes -= data.value.byteLength; | |
if (remainingBytes < 0) | |
throw new RangeError(`Exceeded byte size limit of '${LIMIT}'`); | |
chunks += decoder.decode(data.value); | |
} | |
do_not_optimize(JSON.parse(chunks)); | |
} catch {} | |
} | |
} | |
}); | |
register("LimitedBytesTransformStream", async (list) => { | |
for (let i = 0; i < list.length; i++) { | |
const stream = list[i].body; | |
if (stream != null) | |
try { | |
do_not_optimize( | |
await new Response( | |
stream.pipeThrough(new LimitedBytesTransformStream(LIMIT)), | |
).json(), | |
); | |
} catch {} | |
} | |
}); | |
}); | |
// Start the benchmark | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment