Skip to content
Myr

bench.mts

This file

Path

benchmarks/fetch/bench.mts

118 lines · 4.0 KiB · TypeScript

Last changed by

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

History of this file

Take it

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 1–13why, one step back
1// Measure app.fetch() overhead in-process.
2//3// bun bench.mts / node bench.mts ... benchmark the working tree4// ./compare.sh [ref] ... also benchmark <ref> and compare5//6// Each invocation benchmarks a single variant so that results are not7// affected by same-process JIT/GC order effects. compare.sh spawns one8// process per variant per round and aggregates the results.9//10// Env:11// HONO_SRC ... path to the hono `src` directory to benchmark (default: ../../src)12// HONO_LABEL ... label used in the output (default: hono)13// HONO_JSON=1 ... suppress mitata output and print a single JSON line instead

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 14why, one step back
14// HONO_CASE ... run only cases whose name starts with this prefix (e.g. "ping")

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 15–17why, one step back
15//
16// Runs on both Bun and Node.17import './ts-resolve.mjs'

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 18–19why, one step back
18import { run, bench, measure } from 'mitata'
19import { fileURLToPath, pathToFileURL } from 'node:url'

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

line 20why, one step back
20

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

line 21why, one step back
21const src = process.env.HONO_SRC ?? fileURLToPath(new URL('../../src', import.meta.url))

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 22–40why, one step back
22const label = process.env.HONO_LABEL ?? 'hono'
23const asJson = process.env.HONO_JSON === '1'2425// eslint-disable-next-line @typescript-eslint/no-explicit-any26const makeApp = async (src: string): Promise<any> => {27 const { Hono } = await import(pathToFileURL(`${src}/index.ts`).href)28 const { RegExpRouter } = await import(pathToFileURL(`${src}/router/reg-exp-router/index.ts`).href)2930 const app = new Hono({ router: new RegExpRouter() })31 /* eslint-disable @typescript-eslint/no-explicit-any */32 app33 .get('/', (c: any) => c.text('Hi'))34 .post('/json', (c: any) => c.req.json().then(c.json))35 .get('/id/:id', (c: any) => {36 const id = c.req.param('id')37 const name = c.req.query('name')38 c.header('x-powered-by', 'benchmark')39 return c.text(`${id} ${name}`)40 })

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 41–45why, one step back
41 .get('/user', (c: any) => c.json({ id: 123, name: 'Alice', roles: ['admin', 'editor'] }))
42 .use('/mw/*', async (_c: any, next: any) => {43 await next()44 })45 .get('/mw/hello', (c: any) => c.text('mw'))

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 46–52why, one step back
46 return app
47}4849const app = await makeApp(src)5051const ping = new Request('http://localhost/')52const query = new Request('http://localhost/id/1?name=bun')

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 53–54why, one step back
53const user = new Request('http://localhost/user')
54const mw = new Request('http://localhost/mw/hello')

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 55–57why, one step back
55
56let sink: unknown57

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 58–60why, one step back
58const caseFilter = process.env.HONO_CASE
5960const allCases: [string, (app: any) => Promise<unknown>][] = [

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 61–62why, one step back
61 ['ping GET /', (app) => app.fetch(ping)],
62 ['query GET /id/1?name=bun', (app) => app.fetch(query)],

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 63–64why, one step back
63 ['json GET /user', (app) => app.fetch(user)],
64 ['middleware GET /mw/hello', (app) => app.fetch(mw)],

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 65–77why, one step back
65 [
66 'body POST /json',67 (app) =>68 app.fetch(69 new Request('http://localhost/json', {70 method: 'POST',71 headers: { 'content-type': 'application/json' },72 body: '{"hello":"world"}',73 })74 ),75 ],76]77

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 78–88why, one step back
78const cases = caseFilter ? allCases.filter(([name]) => name.startsWith(caseFilter)) : allCases
79if (cases.length === 0) {80 throw new Error(`no cases match HONO_CASE=${caseFilter}`)81}8283// Warm up before registering benches: the first fetch builds the router84// lazily (>500µs), which makes mitata skip batching for the first bench.85for (const [, fn] of allCases) {86 sink = await fn(app)87}88

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 89–95why, one step back
89for (const [name, fn] of cases) {
90 bench(name, async () => {91 sink = await fn(app)92 })93}9495if (asJson) {

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 96–97why, one step back
96 // Force batching on: without it, each iteration is timed individually at
97 // timer granularity (~41ns on Apple Silicon), which is too coarse here.

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

line 98why, one step back
98 const results: Record<string, { avg: number; min: number; p75: number }> = {}

Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90

lines 99–110why, one step back
99 for (const [name, fn] of cases) {
100 const stats = await measure(101 async () => {102 sink = await fn(app)103 },104 {105 warmup_threshold: Number.MAX_SAFE_INTEGER,106 batch_threshold: Number.MAX_SAFE_INTEGER,107 }108 )109 // p50 rather than avg: insensitive to the slow JIT tier-up windows110 results[name] = { avg: stats.p50, min: stats.min, p75: stats.p75 }

chore(benchmark): add app.fetch() overhead benchmark (#5117)Yusuke Wadabefore adoptionc285f9a

lines 111–118why, one step back
111 }
112 console.log(JSON.stringify({ label, cases: results }))113 console.error(typeof sink)114} else {115 console.log(`benchmarking: ${label} (${src})`)116 await run()117 console.log(typeof sink)118}