← Runtimes
Runtimes

Optimization, AOT, and JIT

Doing less work without changing what the program does.

Optimization changes the work a program performs while preserving the behavior its execution contract requires.

Outcome

Judge whether an optimization keeps observable behavior, predict how undefined or defined overflow constrains it, and explain why speculation needs guards and deoptimization.

Terminology (7)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

As-if rule
An implementation may change the computation while preserving observable behavior allowed by the language for defined executions.
Constant folding
Computing an operation on constants at compile time.
Inlining
Replacing a call with the body of the function it calls.
Ahead-of-time (AOT)
Compiling to machine code before the program runs.
Just-in-time (JIT)
Compiling to machine code while the program runs, using what it has observed.
Deoptimization
Reconstructing a less-specialized execution state when optimized assumptions fail, so execution can continue correctly.
On-stack replacement (OSR)
Switching a function that is still running, such as a long loop, to newly optimized code.

What a speedup must preserve

Compilation determines a representation; optimization searches for an equivalent way to execute it. Constant folding computes a known expression early, and inlining exposes a called function’s body to further simplification. Equivalence includes required output, side effects and defined failures, so discarding a return value does not automatically make the call removable.

Ahead-of-time compilation happens before execution. Just-in-time compilation happens during execution and can use observed values or types to specialize code. When a specialization depends on an assumption that may stop holding, it needs a guard and a correct fallback or deoptimization path. Judging either strategy combines the language’s rules, the build mode and evidence from the actual artifact.

01Less work

What happens to a loop whose answer is predictable?

The billing engineer wants faster daily totals and smaller cached price rules. First check whether the benchmark still performs the work being measured. Then check which results and audit events the proposed speedup must preserve. AOT compilation can specialize from static knowledge; JIT compilation can also use runtime feedback. Both operate within the language and build mode’s required behavior on defined executions.

The daily-total benchmark repeats a loop, but source iterations do not establish how much work the built artifact performs. An optimizer can replace defined computations with an equivalent result. The selected assembly or JIT trace shows which transformation this build chose.

Each program is a billing benchmark. It totals a synthetic day of 1,000,000 orders, where order i costs i cents, with a loop.

The benchmark calls dayTotalCents 200 times. Its retained --trace-opt run reports a TurboFan job; repetition does not guarantee a particular tier on every run.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Billing benchmark: totals a synthetic day of orders, where order i costs i cents.

function dayTotalCents(orders: number): number {
  let cents = 0;

  for (let order = 0; order < orders; order++) {
    cents += order;
  }

  return cents;
}

let last = 0;

for (let run = 0; run < 200; run++) {
  last = dayTotalCents(1_000_000);
}

console.log(`day total for 1000000 orders: ${last} cents`);
The retained Node 22 --trace-opt run contains lines about dayTotalCents. What do those lines report?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --strict && node --trace-opt main.js

Predict the selected source/build pair before revealing the recorded arm64 results. Notes compare specific versions and flags: the Go total assumes the recorded 64-bit int target, and the C++ counter uses the recorded 32-bit int. The C++ overflow probe has undefined behavior and no portable output to reproduce. Trace timings and tier choices are historical observations, not schedules or performance guarantees.

02Assumptions

What may an optimizer assume about overflow?

Before simplifying the counter guard, check its arithmetic contract. Go’s int32 result is defined even on overflow. Rust’s checked and unchecked build modes specify different behavior. The C++23 signed-overflow execution is undefined, so its printed outcomes are records rather than a portable specification.

Order ids come from a 32-bit counter. Before issuing the next id, each program’s guard checks that the last id plus one is still larger, and runs it at the largest 32-bit value.

JavaScript numbers are 64-bit floating point; there is no 32-bit addition here.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Order ids come from a 32-bit counter. Before issuing the next id, check that it is still larger.

function hasNextId(lastId: number): boolean {
  return lastId + 1 > lastId;
}

console.log(`hasNextId(2147483647): ${hasNextId(2147483647)}`);
What does the program print?

03JIT

How can a JIT optimize on a guess?

The checkout path gives a runtime compiler information the static benchmark did not: values and representations seen so far. A specialized fast path needs proof or checks before using restricted assumptions. In the question’s model, a failed type guard triggers deoptimization. Real engines may use local fallbacks or multiple specializations. AOT compilers also propagate constants, specialize known calls, and can use profiles or guards; specialization is not exclusive to JITs.

Consider JavaScript orderTotal(subtotal, shipping) returning subtotal + shipping. An authored integer-only JIT fast path uses a type guard whose failure triggers deoptimization. Calls have passed cents as integers; now shipping is a string from a form field. What happens in this model?

04Practice

Finish the peephole optimizer

Apply the billing engineer’s preservation check to cached price-rule bytecode. The authored VM defines cents arithmetic, a divide-by-zero error and LOG audit output. A call can matter even when its returned price is discarded. The supplied passes let the final task study how inlining exposes folding and dropping creates more opportunities. This finite model does not reconstruct LLVM, Go, V8 or a production engine.

The pricing engine’s peephole optimizer

Fold without changing errors, drop only unused values, then optimize the rules to a fixed point.

  1. easy · R-OPT-V4-1 Fold without changing errors
  2. medium · R-OPT-V4-2 Drop only unused values
  3. hard · R-OPT-V4-3 Optimize to a fixed point
In the frontend The cached price matches, but an audit event disappears Optional

Review this proposed server-side pricing cache. Its contract requires audit(cents) on every quote call. In one fresh module instance, call quote(1000, audit) twice with the same recording callback. Compare returned values and callback events.

This diagnostic uses ordinary calls and a Map, without measuring a framework cache or JIT transformation.

lib/pricing.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const totals = new Map<number, number>();

export function quote(cents: number, audit: (cents: number) => void): number {
  const cached = totals.get(cents);
  if (cached !== undefined) return cached;
  audit(cents);
  const total = cents + 300;
  totals.set(cents, total);
  return total;
}

Both calls return 1300, but only the first records audit(1000). Equal return values do not satisfy the stated per-call audit contract. Cache availability across requests or instances is a separate deployment question; this diagnostic compares two calls to the same supplied instance.

Sources: ECMAScript: Map.prototype.get.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.