Inlining functions
Annotate a small helper with /** @inline */ to expand every call site—even across modules—into the function's body at build time.
In short
- Small, pure helpers only: single-expression functions referencing only parameters and safe globals (such as
Math). - When it helps: V8 already inlines hot functions on its own;
@inlinemainly helps cold paths and lets the loop rewrite see through helper calls. - Tail recursion:
/** @loop */compiles self-tail-recursive functions into a loop so deep recursion never overflows the stack.
✓ Accepted0 diagnostics
ts
/** @inline */
export const max = (...numbers: number[]): number => Math.max(...numbers);
export function widest(a: number, b: number, c: number): number {
const two = max(a, b);
const three = max(two, c);
return two + three + max(three, 0);
}ts
/** @inline */
export const max = (...numbers: number[]): number => Math.max(...numbers);
export function widest(a: number, b: number, c: number): number {
const two = (Math.max(a, b));
const three = (Math.max(two, c));
return two + three + (Math.max(three, 0));
}Benchmark
xs.reduce((sum, x, i) => sum + widest(x, xs[i - 1] ?? 0, 500), 0)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
/** @inline */
export const max = (...numbers: number[]): number => Math.max(...numbers);
export function widest(a: number, b: number, c: number): number {
const two = max(a, b);
const three = max(two, c);
return two + three + max(three, 0);
}Compiled by safe-ts
/** @inline */
export const max = (...numbers: number[]): number => Math.max(...numbers);
export function widest(a: number, b: number, c: number): number {
const two = (Math.max(a, b));
const three = (Math.max(two, c));
return two + three + (Math.max(three, 0));
}Setup and timed expression
const xs = Array.from({ length: 1000 }, (_, i) => (i * 7919) % 1000);
// timed:
xs.reduce((sum, x, i) => sum + widest(x, xs[i - 1] ?? 0, 500), 0); 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 251 B (163 B gzip) · Compiled by safe-ts 272 B (165 B gzip).
The Compiled tab shows the result: max(a, b) is Math.max(a, b). A rest parameter that the body only spreads (...numbers) takes whatever the call passes, including spread arguments: max(...values) becomes Math.max(...values).
Is it faster?
Often not, once the code is hot. Hot code is where V8 is best, and it inlines small functions, rest parameters included, on its own: on Node 26, with warm code and each variant in its own process, this example runs at the same speed as written and compiled. The benchmark above runs both variants in one worker, one after the other, which can favour one of them, so treat a large difference there with suspicion and measure in your own setting. Measured the same way on Node 26, different ways of writing widest:
widest, written as | random input | sorted input |
|---|---|---|
ternaries (a > b ? a : b), recomputed | 1.27 ns | 1.35 ns |
the same with a call to a rest-parameter max for the last one | 1.26 ns | – |
| ternaries, reusing intermediate results | 1.37 ns | 1.10 ns |
Math.max, reusing intermediate results (the example) | 0.89 ns | 0.84 ns |
Two things stand out. The call to max costs nothing once V8 has optimized it. And Math.max beats the hand-written ternary: V8 turns it into a single CPU instruction, while a > b ? a : b is a branch the processor has to guess, which it often gets wrong on varied data.
Where @inline helps is what V8 doesn't see: code that isn't hot yet, call sites that see many different functions, and chains the loop rewrite can only fuse once a callback's helper calls have become plain operators it can see have no side effects.
Versions picked by argument count
A function with a rest parameter can also list fixed-arity versions after the tag: a call with two arguments becomes max2's body, one with three becomes max3's, and any other call uses the function itself.
✓ Accepted0 diagnostics
ts
/** @inline */
export const max2 = (a: number, b: number): number => Math.max(a, b);
/** @inline */
export const max3 = (a: number, b: number, c: number): number => Math.max(Math.max(a, b), c);
/** @inline max2 max3 */
export const max = (...numbers: number[]): number => Math.max(...numbers);The versions must give exactly the same results as the function, and SAFE-TS can't check that for you. (a, b) => (a > b ? a : b) looks like a maximum but isn't Math.max: with NaN it returns the other argument (Math.max returns NaN), and max(-0, 0) and max(0, -0) give different zeros. With such a version, max(NaN, 1) would be 1 while max(NaN, 1, 2) is NaN.
Arguments run once, in order
Inlining never changes what the code does. Literals are put in directly; so are variables, when the body calls nothing that could change them in between. Anything else is evaluated once, in order, into a temporary declared on the statement's line:
✓ Accepted0 diagnostics
ts
/** @inline */
export const max2 = (a: number, b: number): number => (a > b ? a : b);
declare function rating(): number;
export function best(threshold: number): number {
const result = max2(rating(), threshold);
return result;
}ts
/** @inline */
export const max2 = (a: number, b: number): number => (a > b ? a : b);
declare function rating(): number;
export function best(threshold: number): number {
let __in1_1_0, __in1_1_1; const result = (__in1_1_0 = rating(), __in1_1_1 = threshold, __in1_1_0 > __in1_1_1 ? __in1_1_0 : __in1_1_1);
return result;
}What can be inlined
The body is pasted into other modules, so it can only use what exists everywhere:
- One expression:
=> expr, or a function whose body isreturn expr;. - Its parameters and globals (
Math,Number, ...), not other names of its module: a module constant or helper, or another@inlinefunction, doesn't exist where the call is. Writemax3out rather than asmax2(max2(a, b), c). - Plain parameters: no defaults, no destructuring. A rest parameter may only be spread (
...numbers) into a call or an array literal. - No
this,arguments, nested functions, assignments,await, or TypeScript-only syntax (as,!, type arguments): the inlined code must also be plain JavaScript.
A function that breaks one of these gets the inline diagnostic, with the reason. A call stays a call (the function still exists) when it spreads its arguments, when no version has its argument count, when a temporary is needed where no statement can hold it (an arrow's expression body), when a spread argument would land in a plain parameter, or when the call site shadows a global the body uses.
Recursion as a loop: @loop
V8 doesn't implement proper tail calls, so recursion a few thousand levels deep throws RangeError: Maximum call stack size exceeded, and every level pays for a call. /** @loop */ on a function turns its self-calls in tail position (return f(...), nothing done after it) into a loop:
✓ Accepted0 diagnostics
ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type List = { readonly value: number; readonly next: Option<List> };
/** @loop */
export function sum(list: Option<List>, total: number): number {
if (list === undefined) return total;
return sum(list.next, total + list.value);
}ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type List = { readonly value: number; readonly next: Option<List> };
/** @loop */
export function sum(list: Option<List>, total: number): number { __tc1: for (;;) {
if (list === undefined) return total;
{ const __tc1_0 = list.next, __tc1_1 = total + list.value; list = __tc1_0; total = __tc1_1; continue __tc1; }
break; }}Benchmark
sum(list, 0)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
import type { Option } from "@evobug_com/safe-ts-std/result";
export type List = { readonly value: number; readonly next: Option<List> };
/** @loop */
export function sum(list: Option<List>, total: number): number {
if (list === undefined) return total;
return sum(list.next, total + list.value);
}Compiled by safe-ts
import type { Option } from "@evobug_com/safe-ts-std/result";
export type List = { readonly value: number; readonly next: Option<List> };
/** @loop */
export function sum(list: Option<List>, total: number): number { __tc1: for (;;) {
if (list === undefined) return total;
{ const __tc1_0 = list.next, __tc1_1 = total + list.value; list = __tc1_0; total = __tc1_1; continue __tc1; }
break; }}Setup and timed expression
let list = undefined; for (let i = 0; i < 1000; i++) list = { value: i, next: list };
// timed:
sum(list, 0); 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 305 B (136 B gzip) · Compiled by safe-ts 399 B (183 B gzip).
The Compiled tab shows the loop: the function body is wrapped in for (;;) { ... }, and return sum(list.next, total + list.value) becomes "compute the new arguments, assign them to the parameters, continue". That is the while loop you would write by hand, and just as fast: on Node 26, a loop that only counts takes 0.33 ns per step either way, against 2.7 ns per step as recursion (8x). Walking this list, where following the pointers costs more than the call, Chrome 152 ran the loop 2.8x faster. It also runs in constant stack: a list of a million elements works, where the recursion overflows after about ten thousand.
All arguments are evaluated before any parameter changes, as in a call (gcd(b, a % b) reads the old a and b). The function must be a named function with plain parameters, and may not contain nested functions (they would see the parameters change), this, arguments, or a self-call inside try. The recursive frames no longer appear in stack traces.
Recursion that isn't in tail position
return n * factorial(n - 1) multiplies after the recursive call returns, so it can't become a loop as written, and tail-call reports it. Pass the running result along instead (factorial(n - 1, product * n)). SAFE-TS doesn't do this rewrite for you: for numbers it changes the order of the operations, and with floating point (a * b) * c isn't always a * (b * c). Recursion that branches (a tree walk calling itself twice) needs an explicit stack, which is a change of algorithm, not a rewrite.
And inlining?
A function rewritten by @loop contains a loop, so it can't be inlined as an expression; it doesn't need to be. The call into it happens once, and the loop does the work. @inline is for small expression bodies that run inside someone else's loop.