Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

bench(aot): what a compiled system buys a frame, and what it does not

yhh95e719d1fbc4
diff --git a/.gitignore b/.gitignore
index 62bee218e..d38aefc61 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,6 +64,8 @@ pipeline/.cooked-verify/
# Projects the AOT end-to-end gate writes and compiles.
pipeline/.aot-e2e/
pipeline/.aot-e2e-probe/
+# What the AOT frame benchmark builds (wasm + the JS twin of its project).
+bench/aot-frame/.build/
pipeline/.cooked-src/
# Hot-update render-verify artifacts (regenerated by verify:render:hotupdate)
pipeline/.hotupdate-verify/
diff --git a/bench/aot-frame/README.md b/bench/aot-frame/README.md
new file mode 100644
index 000000000..b156b0600
--- /dev/null
+++ b/bench/aot-frame/README.md
@@ -0,0 +1,79 @@
+# AOT frame benchmark — what a compiled system buys a real frame
+
+`bench/aot-stage0` measured a system **loop**: QuickJS against native C++, neither of
+them this engine. This measures **this engine**: the same wasm core, the same `App`,
+the same scheduler, the same project file — run once interpreted and once with its
+compiled twin installed (docs/REARCH_AOT.md).
+
+## Run it
+
+```sh
+node bench/aot-frame/build.mjs # needs emsdk; writes .build/
+node bench/aot-frame/frame-bench.mjs # V8, with a JIT
+
+# scale and effort
+BENCH_ENTITIES=20000 BENCH_FRAMES=300 node bench/aot-frame/frame-bench.mjs
+BENCH_REPS=9 node bench/aot-frame/frame-bench.mjs
+```
+
+`build.mjs` emits three things from one source file (`project/src/systems.ts`): the
+compiled twins (`systems.wasm` + `systems.json`, through the real AOT build step) and
+the same file as JavaScript for the interpreted run. One source, two worlds — a
+retyped copy would only ever agree with its own mistakes.
+
+Each configuration runs in its own process, several times, and the **fastest** rep is
+reported: noise on a desktop only ever adds time. The spread beside each row is what
+says how much noise there was. Both worlds' final positions are summed and compared —
+a run where they disagree prints `RESULT MISMATCH` and fails, because two worlds that
+computed different things have no ratio between them.
+
+## What was measured (2026-08-26, i5-14600K, node 24.19.0, Windows)
+
+`the system` is the frame minus an idle run of the same scene. A root transform is
+recomposed every frame whether or not it moved, so the idle run is the same engine
+work minus the system.
+
+Per entity per frame, across the three bodies (a run varies about ±10% here, so
+these are ranges over the bodies AND over repeated runs):
+
+| entities | interpreted | compiled | ratio |
+|---|---|---|---|
+| 1,000 | 181–239 ns | 95–99 ns | 1.8–2.5× |
+| 5,000 | 213–252 ns | 97–117 ns | 1.9–2.3× |
+| 20,000 | 253–301 ns | 142–147 ns | 1.7–2.1× |
+
+**The compiled cost does not move with the body.** Thin is three multiply-adds; heavy
+is four unrolled integration substeps with a square root and a bounce test each. The
+compiled column is the same number for both, at every scale. What a compiled system
+costs today is not its code — it is the row array, the address per component per row,
+the SysCtx and the `Changed` marking the host does around the call. That is the
+measurement REARCH_AOT.md §7.2 was owed: **~110 ns per entity per frame of plumbing**.
+
+**The interpreted cost barely moves with the body either** — under V8 the body is
+JIT-compiled to machine code, so thirty extra flops disappear next to the per-entity
+protocol (a component copy in, a proxy, a write-back). Both sides are plumbing.
+
+So the ~2× here is **entirely the cheaper boundary**, not faster arithmetic, and it is
+the same effect §16 measured for §12.B from the other side.
+
+## What this is NOT
+
+**A no-JIT number, and that is the number AOT exists for.** V8 and JSC compile the
+interpreted body to machine code; iOS, WeChat on iOS and QuickJS do not. On those the
+interpreted body stops being free and starts costing what Stage 0 measured (154–385×
+for the loop alone), while the compiled body still costs nothing. This machine cannot
+run that half: `node --jitless` has no `WebAssembly` at all, so the engine will not
+boot under it. Run it where a JavaScriptCore is:
+
+```sh
+bun bench/aot-frame/frame-bench.mjs # JSC, JIT
+BUN_JSC_useJIT=0 bun bench/aot-frame/frame-bench.mjs # JSC, no JIT — the iOS proxy
+```
+
+If the two Bun numbers are within a few percent the flag was ignored (see
+`bench/README.md`, which documents the same escape for the frame bench beside this one).
+
+It also excludes GPU submission — the app is headless — and this scene is almost
+nothing but the system, so the frame ratio here is close to the system ratio. A real
+game's frame carries rendering, physics and UI that no compiler touches; §14 measured
+that share, and it is what translates these numbers into a frame budget.
diff --git a/bench/aot-frame/build.mjs b/bench/aot-frame/build.mjs
new file mode 100644
index 000000000..945f9d996
--- /dev/null
+++ b/bench/aot-frame/build.mjs
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file build.mjs — what frame-bench.mjs measures, produced once.
+ *
+ * The bench itself is plain .mjs so a JavaScriptCore runtime can run it (that is
+ * the whole point: the no-JIT number is the one that decides AOT). Plain .mjs
+ * cannot read TypeScript, and the pipeline that compiles a project IS
+ * TypeScript — so the two are separated: this builds, the bench runs.
+ *
+ * It emits both halves of the comparison from ONE source file:
+ *
+ * .build/systems.wasm the compiled twins (emcc, through the real AOT step)
+ * .build/systems.json the manifest a runtime installs them with
+ * .build/systems.js the same file as JavaScript, for the interpreted run
+ *
+ * The JS twin's `esengine` import is rewritten to the SDK entry the bench itself
+ * loads. Left as a bare specifier it would resolve to the package's WEB entry —
+ * a second SDK instance with its own component registry, and the two worlds
+ * would not be running in the same engine at all.
+ *
+ * node bench/aot-frame/build.mjs
+ */
+import { existsSync, mkdirSync, copyFileSync, readFileSync, writeFileSync, rmSync, mkdtempSync } from 'node:fs';
+import { createRequire } from 'node:module';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO = resolve(HERE, '..', '..');
+const PROJECT = join(HERE, 'project');
+const OUT = join(HERE, '.build');
+const require = createRequire(join(REPO, 'package.json'));
+
+/** The pipeline's AOT step, bundled the way the CLI bundles it. */
+async function loadPipeline() {
+ const esbuild = require('esbuild');
+ const dir = mkdtempSync(join(REPO, 'pipeline', 'src', '.build-'));
+ const outfile = join(dir, 'aot.mjs');
+ await esbuild.build({
+ stdin: {
+ contents: "export { buildCompiledSystems } from './bundle/buildCompiledSystems';\n"
+ + "export { resolveEmcc, runEmcc } from './bundle/emccPath';\n",
+ resolveDir: join(REPO, 'pipeline', 'src'),
+ loader: 'ts',
+ sourcefile: 'aot-entry.ts',
+ },
+ outfile,
+ bundle: true,
+ format: 'esm',
+ platform: 'node',
+ target: 'node20',
+ // A CommonJS compiler inlined into an ESM bundle loses the `__filename` it
+ // reads at load; external, it is the same package the tests run against.
+ external: ['typescript'],
+ logLevel: 'error',
+ });
+ const mod = await import(pathToFileURL(outfile).href);
+ return { mod, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
+}
+
+async function main() {
+ const { mod, cleanup } = await loadPipeline();
+ try {
+ const emcc = mod.resolveEmcc();
+ if (!emcc) throw new Error('no emcc — run `pnpm emsdk:setup`, or set EMSDK');
+ console.log(`emcc: ${emcc}`);
+
+ const built = await mod.buildCompiledSystems(PROJECT, { mode: 'release', emcc, run: mod.runEmcc });
+ if (!built.ok) throw new Error(`the AOT step refused:\n ${built.errors.join('\n ')}`);
+ if (!built.wasmPath) throw new Error('nothing was compiled — is the @compiled marker still there?');
+
+ rmSync(OUT, { recursive: true, force: true });
+ mkdirSync(OUT, { recursive: true });
+ copyFileSync(built.wasmPath, join(OUT, 'systems.wasm'));
+ writeFileSync(join(OUT, 'systems.json'), `${JSON.stringify(built.manifest, null, 2)}\n`);
+ console.log(`compiled: ${built.manifest.systems.map((s) => s.name).join(', ')}`);
+
+ const esbuild = require('esbuild');
+ const source = readFileSync(join(PROJECT, 'src', 'systems.ts'), 'utf8');
+ const js = (await esbuild.transform(source, { loader: 'ts', format: 'esm', target: 'node20' })).code;
+ const sdk = join(REPO, 'sdk', 'dist', 'index.node.js');
+ if (!existsSync(sdk)) throw new Error(`the SDK node entry is not built: ${sdk}`);
+ writeFileSync(join(OUT, 'systems.js'),
+ js.replace(/from\s*["']esengine["']/, `from ${JSON.stringify(pathToFileURL(sdk).href)}`));
+ console.log(`wrote ${OUT}`);
+ } finally {
+ cleanup();
+ }
+}
+
+main().catch((e) => {
+ console.error('build failed:', e?.stack || e);
+ process.exitCode = 1;
+});
diff --git a/bench/aot-frame/frame-bench.mjs b/bench/aot-frame/frame-bench.mjs
new file mode 100644
index 000000000..562229799
--- /dev/null
+++ b/bench/aot-frame/frame-bench.mjs
@@ -0,0 +1,268 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file frame-bench.mjs — what AOT buys a FRAME, measured rather than argued.
+ *
+ * bench/aot-stage0 measured a system LOOP: 154-385x, QuickJS against native C++,
+ * neither of them the real runtime. This measures the real one: the same engine
+ * wasm, the same App, the same scheduler, the same project file — run once
+ * interpreted and once with its compiled twin installed, on a scene of N
+ * entities carrying a real `Transform`.
+ *
+ * Every number is a frame time, taken with no profiler on: the SDK's own timings
+ * would have measured the timing — its clock reads and query accounting are real
+ * work that a shipped frame does not do.
+ *
+ * The system's own cost is that frame minus an IDLE run of the same scene, which
+ * is a fair subtrahend here: a root transform is recomposed every frame whether
+ * or not it moved (TransformSystem's dirty tag only gates TransformStatic), so
+ * the idle run does the same engine work minus the system.
+ *
+ * It is small, and that is the caveat on the frame ratio rather than a result: a
+ * real game's frame also carries rendering, physics and UI that no compiler
+ * touches (REARCH_AOT.md §14 measured that share).
+ *
+ * The compiled side's cost includes materialising a row array and a SysCtx per
+ * call — the cost §7.2 is owed a number for, and the thin/thick pair is what
+ * separates it from the body.
+ *
+ * WHAT THIS IS NOT: a no-JIT number. Under node or Bun-with-JIT, V8/JSC compile
+ * the interpreted system to machine code too — this is the LEAST favourable
+ * case for AOT, and the platforms AOT exists for (iOS, WeChat iOS, QuickJS) have
+ * no JIT at all. Run it under a JIT-disabled JavaScriptCore for that half:
+ *
+ * node bench/aot-frame/frame-bench.mjs V8, JIT (floor)
+ * bun bench/aot-frame/frame-bench.mjs JSC, JIT
+ * BUN_JSC_useJIT=0 bun bench/aot-frame/frame-bench.mjs JSC, no JIT (iOS proxy)
+ *
+ * Build the artifacts first: node bench/aot-frame/build.mjs
+ *
+ * Every configuration is measured BENCH_REPS times, in its OWN PROCESS, and the
+ * reps are interleaved. One pass of each in one process was not a fair test: the
+ * interpreted body allocates a component copy per entity per frame and therefore
+ * collects garbage, so a heap that fifteen engine modules had already grown
+ * penalised it more than the compiled side — biasing the ratio in the direction
+ * this benchmark exists to be sceptical of. A fresh process per measurement
+ * costs half a second and removes the question.
+ *
+ * Config via env:
+ * BENCH_ENTITIES (5000) BENCH_FRAMES (600) BENCH_WARMUP (120) BENCH_REPS (3)
+ * ESENGINE_WASM_DIR (auto) ESENGINE_SDK (auto)
+ */
+import { existsSync, readFileSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO = resolve(HERE, '..', '..');
+const BUILD = join(HERE, '.build');
+
+const env = (name) => (typeof process !== 'undefined' && process.env ? process.env[name] : undefined);
+const intEnv = (name, def) => {
+ const v = env(name);
+ const n = v == null || v === '' ? NaN : Number(v);
+ return Number.isFinite(n) ? Math.floor(n) : def;
+};
+const ENTITIES = intEnv('BENCH_ENTITIES', 5000);
+const FRAMES = intEnv('BENCH_FRAMES', 600);
+const WARMUP = intEnv('BENCH_WARMUP', 120);
+const REPS = intEnv('BENCH_REPS', 5);
+const DT = 1 / 60;
+
+const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')
+ ? () => performance.now() : () => Date.now();
+
+/** The same scene for every run: a comparison of two engines needs one workload. */
+function mulberry32(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a |= 0; a = (a + 0x6D2B79F5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+function detectRuntime() {
+ if (typeof Bun !== 'undefined') return `bun ${process.versions?.bun ?? '?'} (JSC)`;
+ if (typeof process !== 'undefined' && process.versions?.node) return `node ${process.versions.node} (V8)`;
+ return 'unknown-runtime';
+}
+
+function resolveWasmDir() {
+ const candidates = [env('ESENGINE_WASM_DIR') && resolve(env('ESENGINE_WASM_DIR')),
+ join(REPO, 'build', 'wasm', 'web'), join(REPO, 'desktop', 'public', 'wasm')].filter(Boolean);
+ for (const dir of candidates) {
+ if (existsSync(join(dir, 'esengine.wasm')) && existsSync(join(dir, 'esengine.js'))) return dir;
+ }
+ throw new Error(`no esengine.wasm + esengine.js. Tried:\n ${candidates.join('\n ')}`);
+}
+
+function resolveSdk() {
+ const candidates = [env('ESENGINE_SDK') && resolve(env('ESENGINE_SDK')),
+ join(REPO, 'sdk', 'dist', 'index.node.js')].filter(Boolean);
+ for (const p of candidates) if (existsSync(p)) return p;
+ throw new Error(`no built SDK node entry. Tried:\n ${candidates.join('\n ')}`);
+}
+
+const pct = (sorted, p) => sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))];
+const ms = (x) => x.toFixed(3);
+
+/**
+ * One world, N frames, one number per frame. A `body` of null schedules no
+ * project system — the idle run. `compiled` installs the twins before anything
+ * is spawned, the only moment it can: the rows a twin reads have to be
+ * allocated in the memory it reads.
+ */
+async function measure(sdk, fixture, wasmDir, body, compiled) {
+ const { loadEsengineModule, createHeadlessApp, Transform, Schedule } = sdk;
+ const module = await loadEsengineModule(wasmDir);
+ const app = createHeadlessApp(module);
+ if (compiled) {
+ const manifest = JSON.parse(readFileSync(join(BUILD, 'systems.json'), 'utf8'));
+ const installed = await app.installCompiledSystems(join(BUILD, 'systems.wasm'), manifest);
+ if (installed === 0) throw new Error('the module installed no twins');
+ }
+
+ const world = app.world;
+ const cppRegistry = world.getCppRegistry();
+ const rand = mulberry32(0x1234abcd);
+ const entities = [];
+ for (let i = 0; i < ENTITIES; i++) {
+ const e = world.spawn();
+ world.insert(e, Transform, { position: { x: (rand() - 0.5) * 2000, y: (rand() - 0.5) * 2000, z: 0 } });
+ world.insert(e, fixture.Mover, {
+ dx: rand() - 0.5, dy: rand() - 0.5, speed: 40 + rand() * 80, boost: rand() < 0.5 ? 1 : 0,
+ });
+ entities.push(e);
+ }
+ const systems = { thin: fixture.thinSystem, thick: fixture.thickSystem, heavy: fixture.heavySystem };
+ if (body) app.addSystemToSchedule(Schedule.Update, systems[body]);
+
+ const step = async () => {
+ await app.tick(DT);
+ if (cppRegistry) module.transform_update(cppRegistry);
+ };
+ for (let f = 0; f < WARMUP; f++) await step();
+
+ const samples = new Float64Array(FRAMES);
+ for (let f = 0; f < FRAMES; f++) {
+ const t0 = now();
+ await step();
+ samples[f] = now() - t0;
+ }
+
+ // What the frames actually computed. Two runs that disagree here are not two
+ // measurements of one thing, and the ratio between them means nothing.
+ let checksum = 0;
+ for (const e of entities) {
+ const p = world.get(e, Transform).position;
+ checksum += p.x + p.y + p.z;
+ }
+
+ const sorted = Array.from(samples).sort((a, b) => a - b);
+ return { median: pct(sorted, 50), p95: pct(sorted, 95), checksum };
+}
+
+const CONFIGS = [
+ { key: 'thin interpreted', body: 'thin', compiled: false },
+ { key: 'thin compiled', body: 'thin', compiled: true },
+ { key: 'thick interpreted', body: 'thick', compiled: false },
+ { key: 'thick compiled', body: 'thick', compiled: true },
+ { key: 'heavy interpreted', body: 'heavy', compiled: false },
+ { key: 'heavy compiled', body: 'heavy', compiled: true },
+ { key: 'idle scene', body: null, compiled: false },
+];
+
+/** One configuration, in this process, reported on stdout for the parent. */
+async function child(key) {
+ const config = CONFIGS.find((c) => c.key === key);
+ if (!config) throw new Error(`no such configuration: ${key}`);
+ const sdk = await import(pathToFileURL(resolveSdk()).href);
+ const fixture = await import(pathToFileURL(join(BUILD, 'systems.js')).href);
+ const r = await measure(sdk, fixture, resolveWasmDir(), config.body, config.compiled);
+ console.log(`RESULT ${JSON.stringify(r)}`);
+}
+
+/** The same runtime this is running under — a bench that measured node from bun
+ * would answer a question nobody asked. */
+function measureInProcess(key) {
+ const run = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--one', key],
+ { encoding: 'utf8' });
+ const line = (run.stdout || '').split('\n').find((l) => l.startsWith('RESULT '));
+ if (!line) throw new Error(`no result for "${key}":\n${run.stdout}\n${run.stderr}`);
+ return JSON.parse(line.slice('RESULT '.length));
+}
+
+async function main() {
+ if (!existsSync(join(BUILD, 'systems.wasm'))) {
+ throw new Error('nothing built yet — run `node bench/aot-frame/build.mjs` first');
+ }
+ const wasmDir = resolveWasmDir();
+
+ console.log('='.repeat(72));
+ console.log('ESEngine AOT frame benchmark');
+ console.log(' runtime :', detectRuntime());
+ console.log(' entities :', ENTITIES);
+ console.log(' frames :', FRAMES, `(+${WARMUP} warmup)`);
+ console.log(' wasm dir :', wasmDir);
+ console.log(' reps :', REPS, '(each in its own process; the fastest is reported)');
+ console.log('='.repeat(72));
+
+ const runs = new Map(CONFIGS.map((c) => [c.key, []]));
+ for (let rep = 0; rep < REPS; rep++) {
+ for (const c of CONFIGS) runs.get(c.key).push(measureInProcess(c.key));
+ console.log(`rep ${rep + 1}/${REPS} done`);
+ }
+ /**
+ * The FASTEST rep, and what the reps disagreed by. The minimum rather than
+ * the median because noise on a desktop only ever adds time: a rep that lost
+ * the CPU measured the machine, not the engine, and the spread beside it is
+ * what says how much of that there was.
+ */
+ const of = (key) => {
+ const medians = runs.get(key).map((r) => r.median).sort((a, b) => a - b);
+ return {
+ median: medians[0], lo: medians[0], hi: medians[medians.length - 1],
+ checksum: runs.get(key)[0].checksum,
+ };
+ };
+
+ const idle = of('idle scene');
+ console.log('config frame ms spread over reps the system ns/entity');
+ for (const c of CONFIGS) {
+ const r = of(c.key);
+ const own = c.body ? ms(r.median - idle.median) : '';
+ console.log(`${c.key.padEnd(20)} ${ms(r.median).padStart(8)} `
+ + `${`${ms(r.lo)}-${ms(r.hi)}`.padEnd(17)} ${own.padStart(10)} `
+ + `${c.body ? ((r.median - idle.median) * 1e6 / ENTITIES).toFixed(1) : ''}`);
+ }
+ console.log('-'.repeat(72));
+ for (const body of ['thin', 'thick', 'heavy']) {
+ const i = of(`${body} interpreted`);
+ const c = of(`${body} compiled`);
+ const agree = i.checksum === c.checksum;
+ console.log(`${body}: system ${((i.median - idle.median) / (c.median - idle.median)).toFixed(2)}x `
+ + `frame ${(i.median / c.median).toFixed(2)}x `
+ + `${agree ? 'same result' : `RESULT MISMATCH ${i.checksum} vs ${c.checksum}`}`);
+ }
+ const mismatched = ['thin', 'thick', 'heavy'].some((body) =>
+ of(`${body} interpreted`).checksum !== of(`${body} compiled`).checksum);
+ console.log('-'.repeat(72));
+ console.log('A ratio here is a FLOOR: this runtime has a JIT, and AOT exists for the ones');
+ console.log('that do not. Frame ms excludes GPU submission (headless), and this scene is');
+ console.log('almost nothing but the system — a real frame carries work no compiler touches.');
+ console.log('='.repeat(72));
+
+ if (mismatched) {
+ throw new Error('the two worlds computed different things — the ratios above are meaningless');
+ }
+}
+
+const one = process.argv.indexOf('--one');
+const entry = one >= 0 ? child(process.argv[one + 1]) : main();
+entry.catch((e) => {
+ console.error('bench failed:', e?.stack || e);
+ if (typeof process !== 'undefined') process.exitCode = 1;
+});
diff --git a/bench/aot-frame/project/src/systems.ts b/bench/aot-frame/project/src/systems.ts
new file mode 100644
index 000000000..be5051b8c
--- /dev/null
+++ b/bench/aot-frame/project/src/systems.ts
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The project the frame benchmark measures — one file, run two ways.
+ *
+ * Both bodies move a real engine `Transform`, because that is what a game does
+ * and it is the address path that costs: an engine component's bytes come from
+ * the C++ pools through the bridge, once per row per frame.
+ *
+ * Thin and thick bracket the answer from both sides (bench/aot-stage0 found the
+ * same): a thin body is nearly all loop overhead, which is where an interpreter
+ * is worst and compiled code best; a thick one dilutes that with arithmetic both
+ * sides pay for.
+ */
+import { defineComponent, defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';
+
+export const Mover = defineComponent('BenchMover', { dx: 0, dy: 0, speed: 0, boost: 0 });
+
+/**
+ * Three multiply-adds per entity.
+ *
+ * @compiled
+ */
+export const thinSystem = defineSystem(
+ [Query(Mut(Transform), Mover), Res(Time)],
+ (query, time) => {
+ for (const [, transform, mover] of query) {
+ transform.position.x += mover.dx * mover.speed * time.delta;
+ transform.position.y += mover.dy * mover.speed * time.delta;
+ }
+ },
+ { name: 'BenchThin' },
+);
+
+/**
+ * Four substeps with a bounce test each, unrolled — the subset has no loop but
+ * `rowLoop`. Its weight separates the cost of a BODY from the cost of handing
+ * the row over: if compiled time barely moves between thin and this, what a
+ * compiled system costs is not its code.
+ *
+ * @compiled
+ */
+export const heavySystem = defineSystem(
+ [Query(Mut(Transform), Mover), Res(Time)],
+ (query, time) => {
+ for (const [, transform, mover] of query) {
+ const step = time.delta * 0.25;
+ let x = transform.position.x;
+ let y = transform.position.y;
+ let vx = mover.dx * mover.speed;
+ let vy = mover.dy * mover.speed;
+
+ x = x + vx * step;
+ y = y + vy * step;
+ let d = Math.sqrt(x * x + y * y);
+ if (d > 1000) { vx = -vx; vy = -vy; x = x * (1000 / d); y = y * (1000 / d); }
+
+ x = x + vx * step;
+ y = y + vy * step;
+ d = Math.sqrt(x * x + y * y);
+ if (d > 1000) { vx = -vx; vy = -vy; x = x * (1000 / d); y = y * (1000 / d); }
+
+ x = x + vx * step;
+ y = y + vy * step;
+ d = Math.sqrt(x * x + y * y);
+ if (d > 1000) { vx = -vx; vy = -vy; x = x * (1000 / d); y = y * (1000 / d); }
+
+ x = x + vx * step;
+ y = y + vy * step;
+ d = Math.sqrt(x * x + y * y);
+ if (d > 1000) { vx = -vx; vy = -vy; x = x * (1000 / d); y = y * (1000 / d); }
+
+ transform.position.x = x;
+ transform.position.y = y;
+ transform.position.z = Math.sqrt(vx * vx + vy * vy) * 0.001;
+ }
+ },
+ { name: 'BenchHeavy' },
+);
+
+/**
+ * A body with branches, clamps and a square root — the shape of gameplay code
+ * rather than of a loop.
+ *
+ * @compiled
+ */
+export const thickSystem = defineSystem(
+ [Query(Mut(Transform), Mover), Res(Time)],
+ (query, time) => {
+ for (const [, transform, mover] of query) {
+ const dt = time.delta;
+ const speed = mover.boost > 0 ? mover.speed * 2 : mover.speed;
+ let x = transform.position.x + mover.dx * speed * dt;
+ let y = transform.position.y + mover.dy * speed * dt;
+ if (x > 1000 || x < -1000) {
+ x = Math.max(-1000, Math.min(1000, x));
+ }
+ if (y > 1000 || y < -1000) {
+ y = Math.max(-1000, Math.min(1000, y));
+ }
+ transform.position.x = x;
+ transform.position.y = y;
+ transform.position.z = Math.sqrt(x * x + y * y) * 0.001;
+ }
+ },
+ { name: 'BenchThick' },
+);
diff --git a/tools/check-comment-style.mjs b/tools/check-comment-style.mjs
index 332e5b919..242575115 100644
--- a/tools/check-comment-style.mjs
+++ b/tools/check-comment-style.mjs
@@ -109,9 +109,10 @@ const COMMENT = /^\s*(\/\/|\*|\/\*)/;
* Delimiters, section rules and structured tags carry no prose to measure.
* `@details` is deliberately absent: it is where prose hides. The release tags
* are here because api-surface requires one on every frozen symbol, and a
- * mandatory tag must not spend the budget meant for the contract.
+ * mandatory tag must not spend the budget meant for the contract — which is why
+ * `@compiled` is here too: the AOT build reads it, so it is a declaration.
*/
-const NOT_PROSE = /^\s*(\/\*+\s*$|\*\/|\/\/\s*[=-]+\s*$|\*\s*$|\/\/\s*$)|@(param|returns?|throws|example|see|code|endcode|file|brief|copyright|author|date|public|beta|experimental|internal|deprecated)\b/;
+const NOT_PROSE = /^\s*(\/\*+\s*$|\*\/|\/\/\s*[=-]+\s*$|\*\s*$|\/\/\s*$)|@(param|returns?|throws|example|see|code|endcode|file|brief|copyright|author|date|public|beta|experimental|internal|deprecated|compiled)\b/;
/** A Doxygen file header states why the file exists; that is its job. */
const FILE_HEADER = /@file\b/;