Performance myths
Much of JavaScript's performance folklore dates back to V8's Crankshaft compiler, replaced in 2017 by Ignition and TurboFan (v8.dev) and later Sparkplug and Maglev. SAFE-TS ignores outdated myths and focuses only on optimizations that still measure faster on modern V8.
In short
- Stop avoiding modern JS:
try/catch(on the non-throwing path),for...of,async/await, destructuring,#privatefields, andMap/Setiteration are all fast on current V8. - What still matters: monomorphic object shapes, eliminating hot-loop allocations (Loops), avoiding quadratic
[...acc, x]spreads, hoistingIntlformatters, and returningResultinstead of throwing on common paths. - Measure in your engine: run the interactive benchmarks in these docs or
npm run bench*withSAFE_TS_DEV_CHECKS=0(why).
What old folklore says versus how V8 runs today:
| Old advice | Today |
|---|---|
Avoid try/catch in hot functions | Optimized like any other code. Throwing costs (see why not throw everything); a try that doesn't throw doesn't. |
Avoid for...of, destructuring, spread, default parameters | Optimized; ES2015+ features run as fast as the code they replace (v8.dev). One exception: for...of over a typed array. |
Avoid async/await, write promise chains | await is faster than hand-written .then chains since V8 7.2 (v8.dev). |
| Call functions with exactly as many arguments as parameters | The arguments adaptor frame is gone since V8 8.9; a mismatched call costs about the same as a matching one (v8.dev). |
Avoid Function.prototype.bind, super.x, class fields, #private | All optimized (v8.dev, v8.dev). |
let/const are slower than var | No difference once optimized; const can even help. |
Avoid Map/Set iteration | Fast, and the right tool for keys that come from data. |
instanceof chains are slow | Fine; SAFE-TS prefers match on a tag for exhaustiveness, not speed. One cost to know: q(x) compiles to x instanceof Err, which is nearly free on numbers, strings and plain data, and measurable on a class instance (below). |
What does still matter, and what SAFE-TS helps with:
- Shapes: objects of one kind with the same keys in the same order (Shapes).
- Allocations in hot loops: intermediate arrays from chained
filter/map, which the loop rewrite removes. - Copying what you're collecting:
[...acc, x]on every step of areduceis quadratic (no-accumulating-copy). - Throwing on the common path: return a
Resultinstead (Errors). - Work repeated per call: Intl formatters (
hoist-intl), regexes that backtrack (no-redos). - Measuring: engines change every few weeks (v8.dev), so the main claims in these docs come with a benchmark: in your browser on the Errors, Loops, Inlining and Shapes pages, and in Node with
npm run bench:loops,npm run bench:fusion,npm run benchandnpm run bench:tags(enum tags). Measure your own code without the dev checks.
Enum tags are strings, and that's fast
Would Enum tags be faster as numbers ({ tag: 2 } instead of { tag: "Published" })? Not when V8 has interned the string: comparing two interned strings is one pointer comparison, like comparing two small integers. Tags are interned when they come from string literals in the code (constructors, object literals), from JSON.parse, and from validate<T>, which writes each tag as a literal. Measured with npm run bench:tags on Node 26.13 (ns per tag read, median of 7, 4096 values in random order; a switch is what match compiles to):
| Where the tags come from | 3 variants | 8 variants | 24 variants |
|---|---|---|---|
| Number tags, for comparison | 1.6 | 1.7 | 6.3 |
| String literals in the code | 1.6 | 1.4 | 2.5 |
JSON.parse | 1.4 | 1.4 | 2.5 |
Words cut from a string at runtime (text.split(" ")), then validate<T> | 1.4 | ||
Words cut from a string at runtime (text.split(" ")) | 8.2 | 4.0 | 26 |
Built by a template literal (`Variant${i}`) | 6.9 | 4.0 | 24 |
Interned string tags read within 1.0–1.3× of numbers, and at 24 variants the string switch is faster. Measured one case per process, the gap was 0.1–0.2 ns. A switch on a string that was built at runtime is 2.5–8× slower, because each case compares its characters. That cost doesn't depend on the type of the tag: it comes from building the string. If a value's tag comes from input that isn't JSON (a word of a command line, a URL parameter), check it with validate<T> (or look it up in a table of literals) before reading it in a hot loop: the value it returns carries the literal tag.
So tags stay strings. Numbers would gain no speed, and would cost:
- The wire format. An enum sent as JSON would carry
{ "tag": 2 }, which a reader on the other side must decode with the same table. - Declaration order as a contract. With numbers, reordering or inserting a variant changes what stored and sent values mean: the problem of TypeScript's numeric
enum(no-ts-enum). - What you read. Logs, test failures and
unreachablemessages would show3, not"Archived". Open<K>, a value from a list the server may add to: its known values and"Unknown"are tags of one string type (Proof types).
q on a class instance
q(result) becomes if (result instanceof Err) return result. For a primitive or plain data the check is close to free; on an instance of a class with its own prototype chain the engine walks that chain, which shows on very small operations. Measured by an adopter on a binary protocol encoder (Node 26, median of 9 runs of 1M calls): encoding the smallest packet took 55 ns with an inline try; 61–65 ns through a callback boundary that returned the bytes; 80 ns when the callback returned the encoder object (q(catchProtocol(() => writer.packet(p))), a Writer instance) and q tested that. Return the values (the bytes), not the object that made them, from a function whose result q checks in a hot path.
Typed arrays: loop with an index
for...of over a plain array is as fast as an index loop. Over a typed array (Uint8Array, Float64Array, ...) it is not. On Node 26.13, an FNV-1a hash over 147 456 bytes:
| Loop | Time |
|---|---|
for (let i = 0; i < bytes.length; i++) reading bytes[i] | 127 µs |
The same, reading bytes[i] ?? 0 | 125 µs |
for (const b of bytes) | 408 µs |
bytes.forEach((b) => ...) | 1 032 µs |
for...of or an index loop over the same bytes in a plain number[] | 127 µs |
In a simulation's grid loops, for...of over typed arrays measured 3–9× slower than an index loop, and typed-array forEach 11×. for (const [i, b] of xs.entries()) is slow on plain arrays too (4–7× here, 14× in the simulation): when you need the index, write the index loop. So in a hot loop over a typed array, use an index. With noUncheckedIndexedAccess, bytes[i] is number | undefined. Write bytes[i] ?? 0: V8 already checks the bound on the load, and the ?? costs nothing measurable. bytes[i]! is allowed too, in a loop that checks the bound itself (items[i] may be missing).
The loop rewrite writes the index loop for you when it can tell the value is a typed array: for (const b of bytes) with bytes: Uint8Array, or made with new Uint8Array(n). Elsewhere, and for a typed array's forEach, write the index loop.
Reusable buffers
no-mutable-global forbids a scratch buffer at the top of a module, so an encoder that reused one allocates its output on every call instead. Two things keep that cheap:
- Return the buffer itself, not a
subarrayof it. V8 keeps the bytes of aUint8Arrayof 64 bytes or less on its heap. Taking asubarrayof one (or reading its.buffer) makes V8 move them off the heap first, about 1 µs. Measured on Node 26.13: returning a new 8-byte buffer takes 27 ns, returningsubarray(0, 8)of a 64-byte one 899 ns. Size the buffer exactly and return it, or copy withslice. - To reuse a buffer, give it to an object the caller owns. An encoder made by
createEncoder()keeps its scratch buffer between calls, and the caller holds the encoder (State). The call sites change, since they now pass the encoder along, but the scratch buffer is allocated once again, not on every call, and no two callers share it.
A Uint8Array above 64 bytes is allocated off the heap from the start, about 1 µs on the same machine, with or without subarray. For large messages, the allocations saved by an encoder owned by the caller are what count.
Clearing a reused list
A list refilled on every frame (the sprites to sort, the orders to show) can keep its storage between frames. Clearing it so it doesn't keep the old objects alive is where the forms differ. Measured on Node 26.13, refilling a list of object references, reading it back and clearing it, per frame:
| Clearing | 100 items | 1 000 items |
|---|---|---|
list.fill(undefined, 0, count) on an Option<T>[] | 0.25 µs, 0 B | 2.6–3.1 µs, 0 B |
list.fill(null!, 0, count) (what no-null and no-unchecked-cast report) | 0.24 µs, 0 B | 2.4–3.9 µs, 0 B |
list.length = 0, then push | 0.38 µs, 2.3 kB | 3.9–4.6 µs, 29 kB |
a new [] every frame | 0.36 µs, 2.4 kB | 3.6–4.0 µs, 29 kB |
length = 0 lets V8 drop the storage, so the next frame grows it again: as costly as a new array. The SAFE-TS form is an Option<T>[] with a count, cleared with fill(undefined); the reads check each element, which costs nothing measurable here:
✓ Accepted0 diagnostics
ts
import type { Mut } from "@evobug_com/safe-ts-std/mut";
import type { Option } from "@evobug_com/safe-ts-std/result";
type Order = { readonly id: string; readonly total: number };
/** Puts the big orders into `picked` (kept between calls); returns how many. */
export function pickBig(picked: Mut<Option<Order>[]>, orders: readonly Order[], min: number): number {
let count = 0;
for (const order of orders) {
if (order.total >= min) {
picked[count] = order;
count += 1;
}
}
return count;
}
export function pickedTotal(picked: readonly Option<Order>[], count: number): number {
let sum = 0;
for (let i = 0; i < count; i++) sum += picked[i]?.total ?? 0;
return sum;
}
/** Lets go of the orders, keeps the storage. */
export function release(picked: Mut<Option<Order>[]>, count: number): void {
picked.fill(undefined, 0, count);
}The list belongs to whoever calls these functions, like a reusable buffer (State). A T[] that is only ever overwritten up to a count (never cleared) is fastest, but keeps the last frame's objects alive until they are overwritten.
Benchmark without the dev checks
The Node loader adds the dev checks unless NODE_ENV=production, and so does the Vite dev server (and Vitest). A benchmark run through either measures them: hashing a large state object ran 1.10–1.32× slower with them, and on par without. Turn them off for benchmarks:
sh
SAFE_TS_DEV_CHECKS=0 node --import @evobug_com/safe-ts-transform/register bench/hash.bench.tsIn Vitest, safeTs({ devChecks: false }) in the config the benchmarks use does the same.