Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"typeperf-compare": "pnpm --dir packages/effect exec node typeperf/compare.mjs",
"runtimeperf": "pnpm --dir packages/effect exec node runtimeperf/run.mts",
"runtimeperf-compare": "pnpm --dir packages/effect exec node runtimeperf/compare.mts",
"hostperf": "node packages/effect/benchmark/hostperf/run.ts",
"check-recursive": "pnpm --recursive --filter \"./packages/**/*\" exec tsc -b tsconfig.json",
"check-dist-types": "node scripts/check-dist-types.mjs",
"jsdocs": "effect-jsdocs",
Expand Down
125 changes: 125 additions & 0 deletions packages/effect/benchmark/hostperf/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# hostperf

Runs a small set of Effect runtime benchmarks in Node.js, Bun, Chromium and
WebKit, writes a JSON report and optionally compares it with an earlier report.
A full run takes under a minute; a filtered run on one host takes a few seconds.

## Cases

| Case | One operation |
| ------------------------------------------- | -------------------------------------------------------------- |
| `Effect/yield` | `Effect.yieldNow` |
| `Effect/forkJoin` | fork a child fiber and join it |
| `Queue/queueTake` | offer and take one item through a bounded queue of 16 |
| `Pool/get and release (fixed pool)` | `Effect.scoped(Pool.get(pool))` on an idle pool of 4 |
| `Pool/poolUseContended` | `Pool.use` from one of 8 fibers sharing a pool of 4 |
| `HashMap/set n fresh string keys + get all` | set one new string key, then read it back |
| `Schema/decode struct (valid)` | `Schema.decodeUnknownSync` of a nested struct |
| `app/app-untraced` | one request through two services, a layer and a caught failure |

Cases are defined in `cases.ts`. Each one validates its result before and
after timing.

## Usage

```sh
pnpm hostperf # all cases, all hosts
pnpm hostperf Pool Effect/yield # cases whose name contains a filter
pnpm hostperf --host node,chromium # a subset of hosts
pnpm hostperf --rounds 1 # quicker, less reliable comparisons
pnpm hostperf --list # case names
```

To check a change, record a baseline before it and compare after it:

```sh
git switch main
pnpm hostperf --out tmp/hostperf/main.json
git switch my-branch
pnpm hostperf --baseline tmp/hostperf/main.json
```

The comparison prints `median(baseline) / median(current)` per host and case,
so values above 1 mean the current tree is faster. The 95% interval comes from
a bootstrap that resamples rounds and then the samples inside them, so noise
between processes counts as well as noise between samples. A case is marked
`faster` or `slower` when the whole interval is more than 5% away from 1, and
`same` when the whole interval is within 5% of 1. Anything else is
`inconclusive`; more `--rounds` may settle it.
Reports are only comparable when they come from the same machine and settings.

Browsers come from Playwright. Install them once with
`pnpm exec playwright install chromium-headless-shell webkit`. Bun must be on
`PATH`; the Nix dev shell provides it.

## Measurement

`cases.ts`, `harness.ts` and `entry.ts` are bundled once with Vite into
`tmp/hostperf/bundle/hostperf.js`, so every host runs the same code. Each case
then runs in a fresh process (Node.js, Bun) or a fresh browser context, so JIT
state from one case does not leak into the next. Every round runs every case
once, in that fresh setting.

For each case and round the harness:

1. runs and validates the case once, then keeps running it until the warmup
time has passed;
2. picks a batch size so one batch takes at least `--sample-ms`;
3. times `--samples` batches, stopping early once the round has used
`--max-case-ms` and has at least 3 samples;
4. validates the last result.

Pages are served from an intercepted `http://localhost` origin with
cross-origin isolation headers, which gives browsers their finest
`performance.now()` resolution. The report records the resolution each host
actually had.

| Option | Default | Meaning |
| --------------- | ------- | ------------------------------------ |
| `--rounds` | 3 | fresh processes or pages per case |
| `--samples` | 10 | timed batches per case and round |
| `--sample-ms` | 10 | target duration of one batch |
| `--warmup-ms` | 100 | warmup per case and round |
| `--max-case-ms` | 1000 | time after which a round stops early |
| `--timeout-ms` | 60000 | time after which a round is killed |

## Report

Reports are written to `tmp/hostperf/results/<timestamp>.json` unless `--out`
is given:

```json
{
"schemaVersion": 1,
"createdAt": "2026-11-27T20:30:00.000Z",
"git": { "sha": "8245e5a2...", "dirty": true },
"settings": { "samples": 10, "sampleMs": 10, "warmupMs": 100, "maxCaseMs": 1000, "minSamples": 3, "rounds": 3 },
"durationMs": 33800,
"hosts": [
{
"host": "node",
"runtime": "Node.js v26.13.0",
"timerResolutionMs": 0.0002,
"durationMs": 9400,
"cases": [
{
"name": "Effect/yield",
"operations": 100,
"medianNs": 1331.2,
"minNs": 1302.5,
"maxNs": 1398.0,
"rounds": [
{ "batchSize": 77, "samples": [1331.2, 1329.9], "durationMs": 312 }
]
}
],
"errors": []
}
]
}
```

`samples` are nanoseconds per operation, and the case medians cover the samples
of every round. A host that fails to start, or a case that throws, times out or prints
something other than its measurement, is listed in
`errors` and makes the command exit with code 1. The other hosts still run.
233 changes: 233 additions & 0 deletions packages/effect/benchmark/hostperf/cases.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
import { Context, Data, Effect, Exit, Fiber, HashMap, Layer, ManagedRuntime, Pool, Queue, Schema, Scope } from "effect"

/**
* One measured operation. `run` may return a Promise; sync cases are timed
* without awaiting so the loop adds no microtask cost.
*/
export interface Instance {
readonly run: () => unknown
readonly validate: (result: unknown) => void
readonly dispose?: () => Promise<void>
}

export interface BenchCase {
readonly name: string
/** Logical operations performed by one `run`; results are reported per operation. */
readonly operations: number
readonly make: () => Instance | Promise<Instance>
}

const expectEqual = (actual: unknown, expected: unknown) => {
if (actual !== expected) {
throw new Error(`Expected ${String(expected)}, received ${String(actual)}`)
}
}

const yieldCount = 100
const forkCount = 100
const queueItems = 1_000
const poolSize = 4
const poolGets = 1_000
const contendedFibers = 8
const contendedGets = 8
const hashMapKeys = 1_000
const appRequests = 100

const sumTo = (n: number) => n * (n - 1) / 2

const makePool = async () => {
const scope = await Effect.runPromise(Scope.make())
let next = 0
const pool = await Effect.runPromise(
Pool.make({ acquire: Effect.sync(() => ++next), size: poolSize }).pipe(Scope.provide(scope))
)
return { pool, dispose: () => Effect.runPromise(Scope.close(scope, Exit.void)) }
}

class NotFound extends Data.TaggedError("NotFound")<{ readonly id: number }> {}

class Users extends Context.Service<Users, {
readonly find: (id: number) => Effect.Effect<{ readonly id: number; readonly name: string }, NotFound>
}>()("hostperf/Users") {}

class Greeter extends Context.Service<Greeter, {
readonly greet: (name: string) => Effect.Effect<string>
}>()("hostperf/Greeter") {}

const UsersLive = Layer.sync(Users)(() => {
const users = new Map(Array.from({ length: 90 }, (_, id) => [id, { id, name: `user-${id}` }]))
return Users.of({
find: (id) => {
const user = users.get(id)
return user === undefined ? Effect.fail(new NotFound({ id })) : Effect.succeed(user)
}
})
})

const GreeterLive = Layer.effect(Greeter)(Effect.gen(function*() {
const prefix = yield* Effect.succeed("hello ")
return Greeter.of({ greet: (name) => Effect.sync(() => prefix + name) })
}))

const handleRequest = Effect.fnUntraced(function*(id: number) {
const users = yield* Users
const greeter = yield* Greeter
const user = yield* users.find(id)
return yield* greeter.greet(user.name)
}, Effect.catchTag("NotFound", (error) => Effect.succeed(`missing ${error.id}`)))

const UserSchema = Schema.Struct({
id: Schema.Number,
name: Schema.String,
email: Schema.String,
active: Schema.Boolean,
tags: Schema.Array(Schema.String),
address: Schema.Struct({
street: Schema.String,
city: Schema.String,
zip: Schema.optional(Schema.String)
})
})

export const cases: ReadonlyArray<BenchCase> = [
{
name: "Effect/yield",
operations: yieldCount,
make: () => {
const program = Effect.gen(function*() {
let i = 0
for (; i < yieldCount; i++) yield* Effect.yieldNow
return i
})
return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, yieldCount) }
}
},
{
name: "Effect/forkJoin",
operations: forkCount,
make: () => {
const program = Effect.gen(function*() {
const fibers: Array<Fiber.Fiber<number>> = []
for (let i = 0; i < forkCount; i++) fibers.push(yield* Effect.forkChild(Effect.succeed(i)))
let sum = 0
for (const fiber of fibers) sum += yield* Fiber.join(fiber)
return sum
})
return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, sumTo(forkCount)) }
}
},
{
name: "Queue/queueTake",
operations: queueItems,
make: () => {
const program = Effect.gen(function*() {
const queue = yield* Queue.bounded<number>(16)
yield* Effect.forkChild(Effect.gen(function*() {
for (let i = 0; i < queueItems; i++) yield* Queue.offer(queue, i)
}))
let sum = 0
for (let i = 0; i < queueItems; i++) sum += yield* Queue.take(queue)
return sum
})
return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, sumTo(queueItems)) }
}
},
{
name: "Pool/get and release (fixed pool)",
operations: poolGets,
make: async () => {
const { dispose, pool } = await makePool()
const program = Effect.gen(function*() {
let count = 0
for (let i = 0; i < poolGets; i++) {
if ((yield* Effect.scoped(Pool.get(pool))) > 0) count++
}
return count
})
return { run: () => Effect.runPromise(program), validate: (result) => expectEqual(result, poolGets), dispose }
}
},
{
name: "Pool/poolUseContended",
operations: contendedFibers * contendedGets,
make: async () => {
const { dispose, pool } = await makePool()
const worker = Effect.gen(function*() {
let count = 0
for (let i = 0; i < contendedGets; i++) {
count += yield* Pool.use(pool, () => Effect.as(Effect.yieldNow, 1))
}
return count
})
const program = Effect.all(Array.from({ length: contendedFibers }, () => worker), {
concurrency: "unbounded"
}).pipe(Effect.map((counts) => counts.reduce((a, b) => a + b, 0)))
return {
run: () => Effect.runPromise(program),
validate: (result) => expectEqual(result, contendedFibers * contendedGets),
dispose
}
}
},
{
name: "HashMap/set n fresh string keys + get all",
operations: hashMapKeys,
make: () => {
let round = 0
return {
run: () => {
const prefix = `k${round++}-`
const keys = new Array<string>(hashMapKeys)
for (let i = 0; i < hashMapKeys; i++) keys[i] = prefix + i
let map = HashMap.empty<string, number>()
for (let i = 0; i < hashMapKeys; i++) map = HashMap.set(map, keys[i], i)
let sum = 0
for (let i = 0; i < hashMapKeys; i++) {
const value = HashMap.get(map, keys[i])
if (value._tag === "Some") sum += value.value
}
return sum
},
validate: (result) => expectEqual(result, sumTo(hashMapKeys))
}
}
},
{
name: "Schema/decode struct (valid)",
operations: 1,
make: () => {
const decode = Schema.decodeUnknownSync(UserSchema)
const input = {
id: 1,
name: "Ada",
email: "ada@example.com",
active: true,
tags: ["admin", "ops", "dev"],
address: { street: "1 Main St", city: "London", zip: "N1" }
}
return {
run: () => decode(input),
validate: (result) => expectEqual((result as typeof input).address.city, "London")
}
}
},
{
name: "app/app-untraced",
operations: appRequests,
make: async () => {
const runtime = ManagedRuntime.make(Layer.mergeAll(UsersLive, GreeterLive))
await runtime.runPromise(Effect.void)
const ids = Array.from({ length: appRequests }, (_, i) => i)
const program = Effect.forEach(ids, handleRequest)
return {
run: () => runtime.runPromise(program),
validate: (result) => {
const responses = result as ReadonlyArray<string>
expectEqual(responses[0], "hello user-0")
expectEqual(responses[appRequests - 1], `missing ${appRequests - 1}`)
},
dispose: () => runtime.dispose()
}
}
}
]
25 changes: 25 additions & 0 deletions packages/effect/benchmark/hostperf/entry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Bundle entry shared by every host. It only uses APIs available in browsers,
* Node.js and Bun, and exposes the runner on `globalThis.__hostperf`.
*/
import { cases } from "./cases.ts"
import { measure, type Settings, timerResolutionMs } from "./harness.ts"

const runtime = (): string => {
const g = globalThis as any
if (g.Bun !== undefined) return `Bun ${g.Bun.version}`
if (g.process?.versions?.node !== undefined) return `Node.js ${g.process.version}`
return g.navigator?.userAgent ?? "unknown"
}

const run = async (options: { readonly case: string; readonly settings: Settings }) => {
const benchCase = cases.find((c) => c.name === options.case)
if (benchCase === undefined) throw new Error(`Unknown case ${options.case}`)
return {
operations: benchCase.operations,
runtime: runtime(),
timerResolutionMs: timerResolutionMs(),
result: await measure(benchCase, options.settings)
}
}
;(globalThis as any).__hostperf = { cases: cases.map((c) => c.name), run }
Loading
Loading