← Runtimes
Runtimes

Escape analysis and allocation

What an implementation can prove about where a value lives.

Follow which uses outlive a function before interpreting a build’s allocation counts.

Outcome

Explain how lifetime constrains storage, interpret allocation counts within their recorded build, and decide which model allocations escape through returns, globals, stored references and calls.

Terminology (3)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.

Escape
A value escapes a function when something can still reach it after the function returns.
Escape analysis
An analysis of which references can outlive a boundary, used to support storage and optimization decisions.
Heap allocation
Dynamically allocated storage managed by an allocator and released explicitly or through collection.

What escape analysis establishes

A value escapes a function when uses outside that function can still reach it after the call returns. Escape analysis follows references across a lifetime boundary, including references stored in other values or retained by called functions. That information helps an implementation decide which storage and optimizations are safe.

A source-level object and a physical heap allocation are different observations. An implementation may represent temporary state with local storage, scalar values or no materialized object. Allocation counters report calls that reach their instrumentation in one build; an authored escape model reports conclusions under its stated rules.

01Counting

Which calls allocate?

The checkout team is reviewing a quote-handler change: return plain Money or a pointer/owning box for each cart line. Start with the recorded allocation counters, then ask what changes when a response or cache retains the value. A helper that merely reads the quote should not receive the same model verdict as one that keeps it.

Go, Rust and C++ compare plain Money (cents and a currency code) with a pointer or owning box. TypeScript compares a fresh object with reused scratch storage and prints only an arithmetic result; matching totals do not measure allocation. Predict each recorded observation before revealing it.

The program prints arithmetic results and has no allocation instrumentation. Object semantics do not require an engine to materialize every temporary on a physical heap.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A checkout service prices every cart line on every quote request. One helper
// returns a new Money object per line, the other fills a reused scratch object.
// The language gives the program no allocation count.

type Money = {
  cents: number;
  currency: string;
};

function lineTotal(unitCents: number, quantity: number): Money {
  return { cents: unitCents * quantity, currency: "USD" };
}

function fillLineTotal(target: Money, unitCents: number, quantity: number): Money {
  target.cents = unitCents * quantity;
  target.currency = "USD";

  return target;
}

const scratch: Money = { cents: 0, currency: "USD" };
let total = 0;

for (let unitCents = 0; unitCents < 1000; unitCents++) {
  total += lineTotal(unitCents, 2).cents + fillLineTotal(scratch, unitCents, 2).cents;
}

console.log(`total ${total}`);
Can this program report how many physical heap allocations lineTotal performs per call?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --strict && node main.ts

The quoted counts are historical observations from the recorded builds, not new measurements in this revision. Rust and C++ were recorded without optimization; Go uses noinline helpers and global sinks. Different compilers, optimization settings, inlining and callers can change counts. Compare the same scope when measuring a proposed change.

02Proof

What can an implementation prove?

The allocation counters leave a caller question: what must remain valid after the helper returns? Escape analysis tracks those uses. A local temporary may fit in a frame, registers or no materialized object. A reference that survives a call needs a valid target for that longer lifetime; inlining can move the relevant boundary into the caller.

Who decides where a value lives
LanguageDecided byHow to observe it
TypeScriptThe JavaScript implementation; source does not fix physical placementProfilers and heap snapshots; this program has no counter
GoThe compiler’s escape analysisgo build -gcflags=-m; testing.AllocsPerRun
RustOwnership/storage types guide allocation; optimizers may eliminate itThe code; a counting allocator
C++Automatic/dynamic storage and owning types; allocation calls may be omittedThe code; a counting operator new
A request handler builds a subtotal object, uses it only inside the handler and never returns it or stores it anywhere else. Must that object be a heap allocation?

03The rules

How does an analysis decide what escapes?

For the lab, use an authored, flow-insensitive reachability analysis: mark a value as escaping when it is returned, stored in a global, stored inside another value that escapes, or passed to a function whose parameter summary escapes.

Stored references make the rule transitive, and the order of the statements does not matter: a value stored inside another before that other one is returned still escapes. For calls, the analysis summarizes each function by whether its parameter escapes, then uses that summary at every call.

Functions are listed after their callees, with one optional parameter and no recursive or unknown calls. This model has no branches, aliases, reference overwrites, return-value binding or object-size threshold. A return is an escape root even when a real caller might immediately consume the value.

A quote handler returns resp, stores total in a field of resp, and passes rate to cacheRate, which stores its parameter in a package-level cache. Which of the three escape?

04Practice

Finish the escape analysis

The lab is one model of an escape analysis, run over the quote handler and its helpers: a package-level cache, a logger and a normalizer. It reads simplified function bodies from stdin and prints heap for model escapes and stack for other named allocations. Those labels describe the authored analysis, not measured storage or any one compiler. Each level supplies the parts that already work.

The escape-analysis model

Find direct escapes, follow stored references, then use what called functions do with their parameters.

  1. easy · R-ESCAPE-V4-1 Find direct escapes
  2. medium · R-ESCAPE-V4-2 Follow links
  3. hard · R-ESCAPE-V4-3 Analyse calls
In the frontend Follow a quote through a callback Optional

This child creates a quote only when clicked and passes it to a parent-supplied callback. Does the quote remain reachable after submit returns? Inspect the parent callback: a void return type does not mean it discards its argument. A callback that stores the quote in state or a cache retains it; one that only reads the cents need not. Neither conclusion measures physical allocations.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

type Quote = { total: { cents: number; currency: string } };

export default function QuoteButton({ onQuote }: { onQuote: (quote: Quote) => void }) {
  function submit() {
    const quote: Quote = { total: { cents: 900, currency: "USD" } };
    onQuote(quote);
  }

  return <button onClick={submit}>Send quote</button>;
}

A local declaration does not bound the object lifetime when the callback retains it. Follow quote.total as well as quote. React event handlers run in response to interaction; this static example supplies no parent implementation.

Sources: React: passing event handlers as props,Svelte: callback props for component events.

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.