Skip to content

Loops ​

forEach, map, and filter(...).map(...).reduce(...) are concise to write and easy to read—but chained callbacks allocate intermediate arrays and defeat V8 optimizations when mutating outer variables. SAFE-TS lets you write clean functional chains and compiles them into tight, single-pass loops at build time whenever doing so is faster and semantics-preserving.

In short

  • Write idiomatic chains: chains of array methods (filter, map, flatMap, slice, reduce, some, find, includes, toSorted, ...) rewrite to flat loops automatically when measurably faster and equivalent, also inside larger expressions.
  • Safe fallback: when equivalence can't be proven, your original code stays untouched.
  • Opt-in enforcement: annotate a statement with /** @inline */ to require a loop rewrite and get a diagnostic explaining why if it can't apply.
  • Typed arrays: for (const x of bytes) compiles to an index loop automatically.
  • Inspect rewrites: run safe-ts explain to see every rewrite applied (and why others were skipped). // @safe-ts legacy files skip loop rewrites until migrated.
✓ Accepted0 diagnostics
ts
export type Order = { readonly paid: boolean; readonly amount: number; readonly name: string };

export function revenue(orders: readonly Order[]): number {
  const total = orders.filter((o) => o.paid).map((o) => o.amount).reduce((sum, a) => sum + a, 0);
  return total;
}

export function names(orders: readonly Order[]): string[] {
  const result = orders.map((o) => o.name.toUpperCase());
  return result;
}
ts
export type Order = { readonly paid: boolean; readonly amount: number; readonly name: string };

export function revenue(orders: readonly Order[]): number {
  const __la1 = orders; let __lr1 = 0; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let o = __le1; if (!(o.paid)) continue; { let o = __le1; const __lu1_1 = (o.amount); { let sum = __lr1; let a = __lu1_1; __lr1 = (sum + a); }}}} const total = __lr1;
  return total;
}

export function names(orders: readonly Order[]): string[] {
  const __la2 = orders; const __lr2: any[] = new Array(__la2.length); for (let __li2 = 0, __ln2 = __la2.length; __li2 < __ln2; __li2++) { if (!(__li2 in __la2)) continue; const __le2 = __la2[__li2]!; { let o = __le2; __lr2[__li2] = (o.name.toUpperCase()); }} const result = __lr2;
  return result;
}
Benchmark revenue(orders)
Code that runs

Each version runs on its own, in a fresh copy of this code (TypeScript types are removed first). The setup runs once per version; the last line is what is timed.

As written
export type Order = { readonly paid: boolean; readonly amount: number; readonly name: string };

export function revenue(orders: readonly Order[]): number {
  const total = orders.filter((o) => o.paid).map((o) => o.amount).reduce((sum, a) => sum + a, 0);
  return total;
}

export function names(orders: readonly Order[]): string[] {
  const result = orders.map((o) => o.name.toUpperCase());
  return result;
}
Compiled by safe-ts
export type Order = { readonly paid: boolean; readonly amount: number; readonly name: string };

export function revenue(orders: readonly Order[]): number {
  const __la1 = orders; let __lr1 = 0; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let o = __le1; if (!(o.paid)) continue; { let o = __le1; const __lu1_1 = (o.amount); { let sum = __lr1; let a = __lu1_1; __lr1 = (sum + a); }}}} const total = __lr1;
  return total;
}

export function names(orders: readonly Order[]): string[] {
  const __la2 = orders; const __lr2: any[] = new Array(__la2.length); for (let __li2 = 0, __ln2 = __la2.length; __li2 < __ln2; __li2++) { if (!(__li2 in __la2)) continue; const __le2 = __la2[__li2]!; { let o = __le2; __lr2[__li2] = (o.name.toUpperCase()); }} const result = __lr2;
  return result;
}
Setup and timed expression
const orders = Array.from({ length: 10_000 }, (_, i) => ({ paid: i % 3 !== 0, amount: i % 97, name: `order ${i}` }));

// timed:
revenue(orders);

Warm: median time per run once V8 has optimized the code (p10–p90: the spread of the samples). First run: the very first call, before any optimization, which is closer to code that runs rarely. Measured in a Web Worker in your browser; results depend on the engine and the machine, which is the point of running it here.
Size: As written 411 B (181 B gzip) · Compiled by safe-ts 873 B (329 B gzip).

The chain becomes a single loop: no intermediate arrays, no callback calls. The Compiled tab shows the code that runs, and the benchmark times both in your browser. The loop stays on the same lines, so stack traces and breakpoints still point at what you wrote.

How a chain becomes loops ​

Each step of a chain is one of three kinds:

  • Steps that pass elements on: filter, map, flatMap, flat(depth) with a depth up to 4, and slice(start, end) with bounds written as numbers of 0 or more. In the loop, each hands its result to the next step, one element at a time.
  • Steps that end the loop with a value: forEach, reduce (with or without an initial value), some, every, find, findIndex, findLast, findLastIndex, includes, indexOf, lastIndexOf and at(k) with k written as a number of 0 or more. some, every, find*, includes, indexOf, at and slice stop as soon as the answer is known.
  • Any other method (toSorted, join, concat, reverse, with, a slice with a negative bound, ...) has no loop of its own: the loop before it fills an array, the method runs on that array as written, and a new loop starts over what it returns.

So any combination of methods can be rewritten:

✓ Accepted0 diagnostics
ts
export function tags(chars: readonly string[], show: (tag: string) => void): void {
  chars
    .filter((c) => c === c.toLowerCase())
    .map((c, i) => `${c}[${i}]`)
    .toSorted()
    .forEach((tag) => show(tag));
}
ts
export function tags(chars: readonly string[], show: (tag: string) => void): void {
  { const __la1 = chars; const __ls1_0: any[] = []; let __lk1_0 = 0; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let c = __le1; if (!(
c === c.toLowerCase())) continue; const __lp1_0 = __lk1_0++; { let c = __le1; let i = __lp1_0; __ls1_0.push((
`${c}[${i}]`)); }}} const __ls1_1 = __ls1_0.toSorted(); for (let __li1 = 0, __ln1 = __ls1_1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __ls1_1)) continue; const __le1 = __ls1_1[__li1]!; { let tag = __le1; 

show(tag); }} }
}

becomes a loop for filter and map, toSorted() on the array it built, and a loop for forEach. The index of map is the position in what filter kept (a counter), as it is with the methods. toSorted is not turned into sort on the buffer: measured, V8 sorts a copy either way, and toSorted was as fast or faster.

Holes come out as each method makes them: map and slice keep them, filter, flatMap, forEach, reduce and indexOf skip them, find, findLast, includes and at see them as undefined. The length is read once. packages/std/test/fusion/ compares 420 generated chains with the methods on dense, sparse and empty arrays, NaN and -0 (includes(NaN) is true, indexOf(NaN) is -1), and checks the callbacks of the last step are called the same way.

A chain inside a larger expression gets its loop before the statement when it is the first thing the statement evaluates: send(xs.map(f)), if (xs.some(f)), return [xs.filter(f)], for (const x of xs.filter(f)), or an arrow's expression body, which becomes a block. Anywhere else (ok && xs.filter(f).some(g), a while condition, a ternary branch) it becomes an arrow function called in place, (() => { ...; return result; })(), which measured as fast as the loop before the statement.

What gets rewritten ​

Measured with packages/std/bench/fusion.bench.ts (Node 26; npm run bench:fusion): the chains as written, in a file marked legacy, against the same code through the build, on arrays of 10, 1,000 and 100,000 elements. Nanoseconds and bytes allocated per element:

CodeAs writtenLoopsAllocatedRewritten on its own
filter(...).map((o, i) => ...).forEach(...)11.6–31.21.8–3.824–38 B → 0yes
flatMap(...).filter(...).reduce(...)70–722.0–4.0142–164 B → 0yes
flat().filter(...).reduce(...)24–282.8–5.636 B → 0yes
filter(...).map(...).includes(x), not found8.6–23.61.5–3.424–28 B → 0yes
map(...).reduce(...), no initial value5.6–26.01.8–3.88–13 B → 0yes
filter(f).map(g).reduce(h, 0), functions by name24.8–31.21.9–4.124–28 B → 0yes
Math.max(0, xs.filter(...).map(...).reduce(...))7.8–32.51.3–3.324–28 B → 0yes, before the statement
on ? xs.filter(...).map(...).reduce(...) : 08.5–26.61.3–4.224–28 B → 0–10yes, called in place
map(...).slice(1, 50).join(",")3.4–26.40.01–218–38 B → 0–26yes: stops after 50
map(...).slice(10)4.0–20.72.0–7.916 B → 0–8yes
map(...).join(",")22.4–30.118.9–21.419–29 B, the sameyes: the map
filter(...).map(...).findLast(...)10.0–22.05.8–14.324–34 B → 18yes (slower at 10 elements)
map(...).toSorted(...).map(...)29–13330–106the sameyes: about the same
the tags example above75–21356–170113–212 B → 107–182yes
map(format)10.1–22.42.5–9.9the sameyes
flatMap(...) alone59–6112.4–14.2124–133 B → 54–70yes
findLast(...) alone7.9–24.70.9–3.10–6 B → 0yes
filter(...).toSorted(...)23–8225–95the sameno: the lone filter stays
find(...) alone0.8–2.40.8–3.2noneno
reduce(...) alone, no initial value1.2–3.21.5–3.2noneno

npm run bench:loops measures hand-written loops against the callbacks for the single-step cases: forEach (1.8–2.8 ns against 0.7–1.0) and map (1.4–7.4 against 1.1–1.6) are faster as loops, while a lone filter (2.6–3.4 against 2.3–3.3), reduce (0.5–0.9 against 0.7–1.0) and some (0.6–0.8 against 0.5–0.8) are as fast as their loop. Fewer intermediate arrays also means less garbage collection (v8.dev).

So without @inline, a chain of two or more steps is rewritten, and so are forEach, map, flatMap, flat, findLast and findLastIndex alone. A lone filter, find, some, every, reduce or includes stays a call, also as one step of a longer chain that has a method without a loop on both sides of it (xs.toSorted().filter(f).toReversed()). join always runs on the array the loop built: building the string in the loop was barely faster and allocated twice as much. safe-ts explain lists what was rewritten and why the rest wasn't ("a lone filter is as fast as the loop it would become").

InlineArray: chains that are always loops ​

inlineArray(xs) from @evobug_com/safe-ts-std/array gives xs typed as an InlineArray. Every chain of methods on it becomes loops, as if each statement carried /** @inline */ (below): a lone filter too, and callbacks with side effects run element by element. A chain on it that can't become loops is an error (rule inline), with what to change, instead of a callback that stays without a word:

✓ Accepted0 diagnostics
ts
import { inlineArray, type ReadonlyInlineArray } from "@evobug_com/safe-ts-std/array";

export type Order = { readonly paid: boolean; readonly amount: number };

export function paidTotal(orders: ReadonlyInlineArray<Order>): number {
  const paid = orders.filter((o) => o.paid);
  return paid.map((o) => o.amount).reduce((sum, a) => sum + a, 0);
}

export function total(amounts: readonly number[]): number {
  return paidTotal(inlineArray(amounts.map((amount) => ({ paid: amount > 0, amount }))));
}
ts
import { inlineArray, type ReadonlyInlineArray } from "@evobug_com/safe-ts-std/array";

export type Order = { readonly paid: boolean; readonly amount: number };

export function paidTotal(orders: ReadonlyInlineArray<Order>): number {
  const __la1 = orders; const __lr1 = []; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let o = __le1; if (o.paid) __lr1.push(__le1); }} const paid = (__lr1 as any);
  { const __la2 = paid; let __lr2 = 0; for (let __li2 = 0, __ln2 = __la2.length; __li2 < __ln2; __li2++) { if (!(__li2 in __la2)) continue; const __le2 = __la2[__li2]!; { let o = __le2; const __lu2_0 = (o.amount); { let sum = __lr2; let a = __lu2_0; __lr2 = (sum + a); }}} return (__lr2 as any); }
}

export function total(amounts: readonly number[]): number {
  { const __la3 = amounts; const __lr3: any[] = new Array(__la3.length); for (let __li3 = 0, __ln3 = __la3.length; __li3 < __ln3; __li3++) { if (!(__li3 in __la3)) continue; const __le3 = __la3[__li3]!; { let amount = __le3; __lr3[__li3] = (({ paid: amount > 0, amount })); }} return paidTotal(inlineArray(__lr3)); }
}

At run time it is the array itself: inlineArray returns its argument, nothing is copied, and code built without the transform (a test runner without the loader) runs the methods as written. The methods that make a new array (map, filter, flatMap, slice, concat, toSorted, toReversed, toSpliced, with) are typed to give an InlineArray, so paid above, kept in a variable, still has its chains rewritten. ReadonlyInlineArray is the one for parameters (it can't be changed through them); InlineArray extends Array, and changing one has the same rules as a T[] (a parameter changed needs Mut<...>).

The build knows a value is an InlineArray from the file: inlineArray(...), a variable or parameter declared with the type, and the result of one of its methods. A value that comes from a call or a member (load().orders, cart.lines typed InlineArray) is not recognised yet, and gets the rules of a plain array.

Measured (npm run bench:fusion, ns per element at 10 / 1,000 / 100,000 elements):

Code on an InlineArrayAs writtenLoops
filter(...).map((o, i) => ...).forEach(...)9.4 / 10.3 / 30.32.7 / 1.8 / 2.4
the tags example above66 / 118 / 18258 / 116 / 164
filter(isPaid).map(amountOf).reduce(add, 0), functions imported19.7 / 20.9 / 24.56.7 / 7.3 / 7.6
filter(...) alone4.5 / 5.5 / 5.94.9 / 6.2 / 7.2

Two costs come with "always": a lone filter is a little slower as a loop than V8's filter, and a function imported from another module, used after the first step, gets a loop of its own (the build can't see how many parameters it reads, so it builds the array the third one would be).

Typed arrays ​

On Node 26, for...of over a typed array is several times slower than an index loop (the iterator isn't optimized away). Plain arrays don't have this problem. When the build can tell that the value is a typed array (new Uint8Array(n), or a variable or parameter declared as Uint8Array, Float64Array and so on), it writes the index loop for you:

✓ Accepted0 diagnostics
ts
export function fnv(bytes: Uint8Array): number {
  let hash = 0x811c9dc5;
  for (const byte of bytes) hash = Math.imul(hash ^ byte, 0x01000193) >>> 0;
  return hash;
}
ts
export function fnv(bytes: Uint8Array): number {
  let hash = 0x811c9dc5;
  for (let __ti1 = 0, __ta1 = bytes; __ti1 < __ta1.length; __ti1++) { const byte = __ta1[__ti1]!; hash = Math.imul(hash ^ byte, 0x01000193) >>> 0; }
  return hash;
}

The loop reads length on every step, like the iterator, so break, continue and a buffer that grows while you loop behave the same. One difference: if the buffer is detached (transferred to a worker) during the loop, the loop ends where the iterator would throw.

Arrays filled in place ​

A map allocates a new array. When the array it maps over was made in the same function and this map is its only use, nobody else can see the old values, so the loop writes the results into that array instead (like Rust's in-place collect on an owned Vec):

✓ Accepted0 diagnostics
ts
export function totals(prices: readonly number[], rate: number): number[] {
  const net = prices.map((p) => p * rate);
  const rounded = net.map((n) => Math.round(n));
  return rounded;
}
ts
export function totals(prices: readonly number[], rate: number): number[] {
  const __la1 = prices; const __lr1: any[] = new Array(__la1.length); for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let p = __le1; __lr1[__li1] = (p * rate); }} const net = __lr1;
  const __la2 = net; const __lr2 = __la2; for (let __li2 = 0, __ln2 = __la2.length; __li2 < __ln2; __li2++) { if (!(__li2 in __la2)) continue; const __le2 = __la2[__li2]!; { let n = __le2; __lr2[__li2] = (Math.round(n)); }} const rounded = __lr2;
  return rounded;
}

The second map reuses net's storage: the Compiled tab shows const __lr2 = __la2;. It is 2-5x faster than allocating for arrays of thousands of elements. An array used again later, or one mapped inside a loop or callback that could run more than once, gets a new array as before.

To change an array you own on purpose, updateEach(mut(items), f) from @evobug_com/safe-ts-std/array takes a Mut<T[]> and replaces each element; a call written in place becomes the same in-place loop.

A map without a filter fills a preallocated array (new Array(length)): 1.2-1.6x faster to build than [] and push. V8 then treats the result as possibly having holes, which makes reading it about 0.1 ns per element slower, so it pays off unless the result is read about ten times.

When the code stays a callback ​

The rewrite never changes what the code does, so it only happens when nothing can tell the difference. The loop reads the length once, and skips, keeps or visits holes the way each method does (map keeps them, find sees undefined). Beyond that, it needs:

  • A receiver known to be an array: a variable or parameter typed T[], readonly T[], Array<T> or a tuple, or made with [...], Array.from, Object.keys, .map(...) and so on. Also an imported constant declared as one in its module, and a member whose declared type says so: cart.orders with cart: Cart and type Cart = { orders: Order[] } (or an interface, also from another file). forEach on a Map passes (value, key), so a receiver whose type the rewrite can't see (load().orders, an optional member) stays a callback. A typed array (Uint8Array, ...) isn't one either: its forEach stays a callback, though an index loop is several times faster (Performance myths).
  • No side effects before another step. A chain runs every filter callback before the first map callback; the loop runs them element by element. When the earlier callbacks only compute a value, nobody can tell. When one calls something or assigns, the loop ends after it: its step fills an array, as written, and the next steps loop over that. (The calls a callback may make are reading methods such as toUpperCase, includes or Math.max; a callback passed by name counts as one with side effects, apart from Boolean, Number, String and the like.)
  • A literal or a variable as the other arguments: reduce's initial value, thisArg, includes(x). They are read before the loop starts.
  • No q(...) inside the callbacks, and no await in a chain that is called in place.
  • A migrated file. A file marked // @safe-ts legacy gets no loop rewrites (nor @inline), so the code it ships doesn't change before you migrate it (Adopting SAFE-TS). To keep other files out of every rewrite, use the bundler plugin's exclude option.

A callback can be passed by name (orders.map(format)), have default values or var, or use this with a thisArg: it is then evaluated once before the loop, like the method does, and called with the arguments the method would pass. A callback that reads the third, array parameter after another step (filter(...).map((o, i, all) => ...)) gets the array it asks for: the loop ends before that step and builds it, and so does one that uses the receiver by name after the first step, or passes a function whose parameters the build can't count.

If a callback in a chain throws, the elements before it have already gone through the later steps: xs.map(f).forEach(g) has called g for them, where the methods would have called f for every element first. A chain that stops at its answer (some, find, at, slice) doesn't run the earlier callbacks for the elements after it, so a callback that would have thrown there doesn't. Code that recovers from such a throw and inspects what those steps did is the one place where the result is visible.

@inline: ask for the loop ​

Put /** @inline */ on a statement to say that its chains must become loops. This is also how you vouch for what the rewrite can't check: that a receiver like load().orders is an array, and that fusing the steps is fine (callbacks with side effects run element by element). Every step that can run in a loop does, even alone (a lone filter too), and the other arguments may be any expression. If the statement still can't be rewritten, you get the reason (rule inline) instead of a silent callback:

✓ Accepted0 diagnostics
ts
type Order = { readonly paid: boolean; readonly amount: number };
type Cart = { readonly orders: readonly Order[] };

export function total(load: () => Cart): number {
  /** @inline */
  const sum = load().orders.filter((o) => o.paid).map((o) => o.amount).reduce((a, b) => a + b, 0);
  return sum;
}
ts
type Order = { readonly paid: boolean; readonly amount: number };
type Cart = { readonly orders: readonly Order[] };

export function total(load: () => Cart): number {
  /** @inline */
  const __la1 = load().orders; let __lr1 = 0; for (let __li1 = 0, __ln1 = __la1.length; __li1 < __ln1; __li1++) { if (!(__li1 in __la1)) continue; const __le1 = __la1[__li1]!; { let o = __le1; if (!(o.paid)) continue; { let o = __le1; const __lu1_1 = (o.amount); { let a = __lr1; let b = __lu1_1; __lr1 = (a + b); }}}} const sum = __lr1;
  return sum;
}
✕ Rejectedinline
ts
type Order = { readonly amount: number };

export function labels(orders: readonly Order[], format: (o: Order) => string): string[] {
  /** @inline */
  const result = orders.map(function (o) {
    return format(o);
  });
  return result;
}

A callback that isn't an arrow is copied before the loop, so it must fit on one line: write it as (o) => format(o), or pass format itself.

Reading by index ​

With noUncheckedIndexedAccess, items[i] is T | undefined. In an index loop the loop is the bounds check, and items[i]! is accepted where the checker can prove the read in bounds: member paths (cart.lines[i]!), any integer start, descending loops, neighbours (items[i + 1]! under i + 1 < items.length), a second array of the same length, a check in a while, if or &&, tuples and clamps. The full list is in no-unchecked-cast, and the message says why a read isn't accepted. It relies on every position below the length holding a value, so an array written past its end (slots[n] = 1 leaves holes below n) gets no items[i]! proved, and sparse-array-write reports the write: fill it with push, or keep a table with gaps in a Map.

Indices from data (products[order.product], steps[plan[0]]) are different: nothing in the code says they are in range, so a missing element is a data error, not a "can't happen". Check the index once, where the data is used, and return the error; after that check the reads are accepted. An index with a declared type of small integers (size: 0 | 1 | 2, also after validate<T> has checked it) needs no check over a table of that length:

✓ Accepted0 diagnostics
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

type Product = { readonly name: string };
type Order = { readonly product: number; readonly size: 0 | 1 | 2 };

export type OrderError = Enum<{ NoProduct: { index: number } }>;
export const OrderError = constructors<OrderError>();

const SIZES = ["small", "medium", "large"] as const;

export function describe(products: readonly Product[], order: Order): Result<string, OrderError> {
  const i = order.product;
  if (!Number.isInteger(i) || i < 0 || i >= products.length) return err(OrderError.NoProduct({ index: i }));
  return `${products[i]!.name}, ${SIZES[order.size]!}`;
}
ts
import { constructors, type Enum } from "@evobug_com/safe-ts-std/enum";
import { err, type Result } from "@evobug_com/safe-ts-std/result";

type Product = { readonly name: string };
type Order = { readonly product: number; readonly size: 0 | 1 | 2 };

export type OrderError = Enum<{ NoProduct: { index: number } }>;
export const OrderError = constructors<OrderError>();

const SIZES = ["small", "medium", "large"] as const;

export function describe(products: readonly Product[], order: Order): Result<string, OrderError> {
  const i = order.product;
  if (!Number.isInteger(i) || i < 0 || i >= products.length) return err(({ tag: "NoProduct", index: i } satisfies OrderError as OrderError));
  return `${products[i]!.name}, ${SIZES[order.size]!}`;
}

Where a missing element has a sensible value, say so: steps[plan[0] ?? 0] ?? fallback, or list.at(-1) ?? fallback for the last element.

Rules in this guide: inline, no-unchecked-cast

MIT OR Apache-2.0 · Docs by Gemini 4 Neon Extra