CComputer Science, Built

Act III · Speaking to the Machine

Part 15 of 61

Runtimes

Degreestarts at this level44 min of film17 chaptersprerequisites: Part 11, Part 13, Part 14

Where does a program live while it runs, and who cleans up the memory it leaves behind?

The part opens on the Job's heap as it runs on the virtual machine this part builds: memory fills, the collector stops the program, keeps what is still reachable, and the program carries on. An interpreter is eval and apply; an environment captured with a function's code is a closure; and continuation-passing style turns the call stack into a value, so that a tail call is a jump. The lambda core of Part 14 is compiled to a stack bytecode with tagged words, and the virtual machine is written in the Pebble language and co-simulated with the reference machine on Pebble. Then memory: reference counting and its cycles, mark-sweep and mark-compact, and Cheney's copying collector with its scan and free pointers, whose copying work per allocated word is about L / (S - L) for live data L in a semispace S. Generations exploit short lifetimes, and a collector that runs while the program mutates the heap is kept correct by the tri-colour invariant and a write barrier. The part measures JIT tiers, inline caches, virtual dispatch and exceptions on real runtimes on this machine, assembles a WebAssembly module by hand, and runs the Job, garbage-collected, on the Pebble VM for ledger row 6.

What you need. Recursion and the call stack as Part 11 describes them, and pointers. The lambda core is Part 14's; its types are not needed here.

Mathematics, ideas and history
interpreters, closures, continuations and CPS, bytecode VMs, garbage collection (copying, generational, tri-color), JITs, WebAssembly
What we build or compute
a VM and three garbage collectors

What you will be able to do

Degree

  • Trace eval and apply on a small expression, and show what a closure captures under lexical scope and what dynamic scope would do instead.
  • Hand-compile a small function to stack bytecode and run it on paper.
  • Say which objects reference counting frees and which it misses, and mark a heap from its roots.

Graduate

  • Run Cheney's algorithm on a small heap, with forwarding addresses and the scan and free pointers, and derive the cost L / (S - L).
  • Convert a function to continuation-passing style and explain why proper tail calls bound the stack.
  • State the strong and weak tri-colour invariants, show the move that loses an object, and say which barrier (insertion or deletion) prevents it.

Research

  • State the first and second Futamura projections and what meta-tracing and partial evaluation of interpreters do and do not guarantee.
  • Pose a real-time collection bound with its machine, allocation rate, roots, object sizes and liveness limits made explicit.

Industry

  • Size a heap from the live data and a pause or throughput target, and read a collector's log.
  • Explain a JIT's tiers, inline caches and deoptimization well enough to diagnose code that stays slow after warmup.
  • Compare virtual dispatch and table-driven exceptions by measurement, and say what a WebAssembly validator checks before a module runs.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 18 min · Graduate 40 min · Research 44 min · Industry 26 min.

  1. 0A program needs a place to liveDegree2 min
  2. 1Interpreters: eval and applyDegree2 min
  3. 2Environments and closuresDegree2 min
  4. 3Continuations and tail callsGraduate2 min
  5. 4A bytecode virtual machineDegree3 min
  6. 5The VM, on PebbleGraduate2 min
  7. 6Why collect, and counting referencesDegree3 min
  8. 7Tracing: mark–sweep and mark–compactDegree2 min
  9. 8Cheney's copying collector, and what it costsGraduate2 min
  10. 9GenerationsGraduate2 min
  11. 10Collecting while the program runsGraduate3 min
  12. 11Just-in-time compilersIndustry3 min
  13. 12Dynamic dispatch and exceptionsIndustry2 min
  14. 13WebAssembly, and other machinesIndustry3 min
  15. 14The Job, collectedGraduate2 min
  16. 15Frontier: the limits of runtimesResearch4 min
  17. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

A program needs a place to liveDegree2 min

Part fourteen expressed the Job with functions, lists and pairs. Now we need a machine that runs it. Each double colon in bump creates a list cell; each pair creates another heap object. The source never explicitly frees them. On our chapter passage, the displayed allocation count is much larger than the text itself. Rebuilding an association list creates many temporary objects. A collection finds only the reachable portion. The displayed live peak is the largest collection sample, not an every-instruction maximum. This part builds the runtime that allocates these objects, follows their references and reclaims space safely.

This is the Job's heap as it runs, on the virtual machine this part builds. Memory fills as the program allocates. When the heap is full, the garbage collector stops the program, finds every object it can still reach, and keeps only those. The heap drops back to the live data, and the program carries on, never knowing. Eight times on this text. How the collector finds what is live, how fast it can do it, and how it can do it while the program keeps running, is half of this part.

Here is where we are going. Closures: how a function remembers the place where it was made, long after that place is gone. Continuations: the call stack, turned into a value you can hold. A bytecode virtual machine for the lambda core, written in the Pebble language and running on Pebble itself. Four garbage collectors, and the three-colour invariant that lets a collector run while the program is still changing the heap. And just-in-time compilers, which make dynamic languages fast, measured on real runtimes on this machine.

1Interpreters: eval and applyDegree2 min

An interpreter is a program that takes steps for another program. Our tree-walking interpreter evaluates syntax in an environment: a map from variable names to values. A variable reads that map; arithmetic evaluates its operands and combines their values. A function evaluates to a closure containing its code and the environment it captures. Applying the closure extends that saved environment with the argument and evaluates the body. Eval and apply call each other. This is one implementation model, not a description of every interpreter. Repeated tree visits, name lookup and environment allocation can be expensive. The table measures this particular implementation; bytecode and compilation change where that work happens.

A language can be explained by an interpreter. McCarthy's 1960 Lisp evaluator and Steve Russell's implementation made that idea concrete. An interpreter written in the language it interprets is called metacircular; SICP develops one in its fourth chapter. Our tree evaluator counts the displayed applications and allocated values while running the Job. Its environment-copying strategy is an implementation choice. Repeated syntax inspection and name lookup explain overhead here. Bytecode and compilation can remove or reorganize some of that work; the numbers do not establish a universal cost for every interpreter.

We can compare implementations, provided we name the experiment. The table times recursive Fibonacci of thirty-two inside each process, taking the best of three fresh runs. It does not include process startup. The same source-level computation meets different code generators, optimizers and runtime policies. Interpreter-only switches help expose some of those choices. These are single-host measurements with the displayed versions, not a ranking of languages. A compiler can transform this particular recursion, and another workload may behave differently. For the Job, our tree walker and bytecode VM also report their own operation counts. Keep those logical operations separate from native nanoseconds and the Pebble instruction counts to come.

2Environments and closuresDegree2 min

Which binding should a function see? Here x is one when f is defined, but a new x with value ten surrounds its call. Lexical scope uses the definition-site binding, so f of zero is one. Our contrasting dynamic interpreter uses the caller's environment and produces ten. These are actual runs of the two small models. Lexical scope lets us resolve a name by the program's structure. Languages may also provide dynamic bindings for selected variables; modern Emacs Lisp supports lexical binding as well. Historical defaults are not a rule that every language must choose only one mechanism.

A returned function can outlive the call that created it. make_adder returns a function that still needs n. Keeping only a pointer into the vanished stack frame would be unsafe. A closure packages the function's code with its captured values. Our VM puts that environment on its heap. Escape analysis and other implementations may choose a different representation. The two returned adders retain different values of n, so their answers differ even though they share code. Lexical scope says which binding a function uses; closure conversion explains how to preserve that binding when functions escape. Scope rules and storage placement are separate choices.

A compiler turns this into something a machine can run by closure conversion. Our compiler finds the free variables of every inner function, here just n. In make_adder, the CLOSURE instruction copies n into a new heap object, next to a reference to the inner function's code. Inside that code, FREE zero reads n back out of whichever closure is running. So add five and add seven are two small objects, holding five and seven, that share one block of code. Copying the values is called a flat closure. The alternative is to keep a pointer to the enclosing frame, itself on the heap: cheaper to build, slower to use, and more likely to keep garbage alive, which is why Shao and Appel studied which to choose.

3Continuations and tail callsGraduate2 min

A call computes a value and remembers the pending work. In direct factorial, multiplication waits for the recursive result, so our VM keeps frames. In continuation-passing style, k represents what to do next. A new closure remembers multiplication by n and the previous continuation. For factorial of a thousand, the table counts logical stack and heap slots in our Python reference VM. Its arbitrary-precision arithmetic is not Pebble's fixed-width arithmetic; these counts exclude the host's big-integer storage and computation. Pending work moves into closures and becomes explicit data. CPS is a useful compiler representation, including in influential ML and Scheme compilers.

When no work waits after a call, the caller's frame can be reused. The Job's character loop calls words in tail position. Our compiler marks that position and the VM turns the call into a jump with arguments. On the measured chapter, disabling this optimization greatly increases the deepest stack. Reusing tail-call frames does not bound the entire Job independently of its input. The table-update function bump still has non-tail recursive work. Our separate tests with twenty, eighty and two hundred distinct words show its stack growing with vocabulary. Proper tail calls bound the active tail-call chain. Scheme requires them; other implementations differ. Always identify which recursion is tail recursive before making a space claim.

A program can capture its continuation. call/cc passes a representation of the current continuation to a function. In product_exit, invoking it with zero abandons the multiplications waiting between the capture and the invocation. Our CEK machine makes this concrete with control, environment and linked continuation frames. The measured list produces zero multiplications in the escaping version, while ordinary product performs the displayed work. Continuations can express exceptions and, with suitable protocols, coroutines. Control transfer does not undo arbitrary effects. The classical type of call/cc connects this jump to Peirce's law, beyond the pure intuitionistic core studied in Part fourteen.

4A bytecode virtual machineDegree3 min

A bytecode VM replaces repeated syntax-tree dispatch with a compact instruction stream. Our instructions load locals, call functions, construct heap values and branch. The displayed list is this VM's instruction set, not a universal bytecode standard. Pebble stores a value in a thirty-two-bit word. One tag bit distinguishes integers from aligned heap pointers, leaving a signed thirty-one-bit integer payload. The Python reference VM uses unbounded Python integers, so its large factorial experiment is a logical-slot model. Agreement with the physical Pebble VM is checked on the tested in-range programs, not asserted for arbitrary-precision arithmetic.

Here is bump, from Part 14, and the bytecode our compiler makes of it. Locals live in numbered slots: w is slot zero, table slot one. The match stores the table, tests it against the empty list with JNIL, and if it is a cell, takes it apart with HEAD and TAIL into slots for p and rest. The comparison fst p equals w is FST, LOCAL, EQ, and a conditional jump. And at the end, the recursive call, followed by a CONS that is waiting for its result. That waiting CONS is why bump, unlike words, needs a stack frame for every entry of the table it walks past. Thirty-seven instructions; the whole Job, with its driver, is under four hundred.

Where does the time go? We counted every instruction the VM executed on a passage of thirteen hundred bytes: four hundred and sixty thousand. The biggest bar is not arithmetic or list building. It is LOCAL: pushing a local variable onto the stack. With SETLOCAL, its opposite, it is more than half of everything the machine does. A stack machine spends most of its effort shuffling values to where the next instruction can find them, and every shuffle pays the full price of an instruction: fetch it, decode it, jump to its handler.

Real languages make the same choice. This is CPython's bytecode for bump written in Python, printed by the dis module on this machine: LOAD_FAST, LOAD_CONST, BINARY_SUBSCR. It is a stack machine, like ours. The alternative is a register machine, where one instruction names its operands: add register one to register two into register three, instead of four stack instructions. Lua made that switch in version five in 2003, and a careful study by Shi and colleagues found a register machine executes forty-seven percent fewer instructions, for code a quarter larger. Both survive. Stack code is compact and trivial to generate, which is why the JVM, CPython and WebAssembly use it. Register code does more work per dispatch, which is why Lua, Android's Dalvik and V8's interpreter use registers.

5The VM, on PebbleGraduate2 min

A virtual machine is just a program, and we have a machine and a compiler of our own. So we wrote the virtual machine in the Pebble language of Part 13, compiled it, and ran it on Pebble. Its heart is this loop. Fetch the opcode and its argument, then test the opcode against each instruction in turn, and run the matching handler. Here is the handler for CONS: if the heap is full, collect; then write a header and two fields, and push a pointer. A loader at the start reads the compiled Job, byte by byte, and then the VM reads the text. The stack, a heap of two halves, and the collector all fit in Pebble's one megabyte of memory. The Pebble language has no switch statement and no bit shifts, so dispatch is a chain of ifs, and a tag is taken apart with division and remainder. Both turn out to matter.

Two implementations give us an opportunity to cross-check. Run the same in-range Job passage on the Python reference VM and the Pebble implementation. Their output, bytecode work, collection counts, copied words and deepest stack are checked as shown. This is finite cosimulation evidence for these programs and heap settings. A mismatch would still be valuable: it would identify a concrete counterexample to investigate.

Dispatch order changes the work of our Pebble interpreter. With its chain of tests, the same passage executes about forty-seven instructions per bytecode when frequent opcodes come first, sixty in opcode order, and a hundred in the reversed frequency order. These are instruction counts, not measured elapsed-time ratios. Our separate C experiment compares a switch with computed-goto threading. Its current timings are displayed; they belong to this tiny loop, compiler and host. A per-handler indirect branch can expose different prediction history, but modern predictors, compiler transformations and workload structure affect the result. Measure the generated implementation before applying an old performance rule.

6Why collect, and counting referencesDegree3 min

An allocator finds space; a collector decides which space can safely be reused. The roots are the references held by active program state, including the stack and globals in our VM. Follow their pointers through the heap. An unreachable object cannot be accessed again through these references, under this model's rules. Reachability is conservative: an object can remain reachable even if the program will never use it again. It is not the same as semantic last use. Our core omits weak references and finalizers. Real runtimes need additional rules for them, but the root-to-object graph is the starting point for tracing collection.

Reference counting attaches a count to each object. In this simple model the count records incoming owned references, including roots. Creating or copying a reference increments the count; overwriting or dropping one decrements it. When the root is removed, a reaches zero and is reclaimed. Releasing its outgoing reference can make b reach zero, and then c. Watch that cascade through the graph. This is prompt reclamation, but a large graph can cause a large synchronous cascade.

Counting has one famous weakness. Two objects that point at each other each have a count of one, even when nothing else can reach them. They are garbage, and their counts will never reach zero. We can watch this happen in CPython on this machine. Make a hundred thousand pairs of objects that point at each other, with automatic collection switched off, and then call the collector by hand. It finds almost two hundred thousand objects that reference counting had left behind: every pair except the last, which the variables x and y still hold. So CPython does both: it counts references, and it also runs a tracing collector to find cycles, itself generational, with thresholds you can read and tune. In our own VM, a recursive closure refers to itself through the SELF instruction rather than a pointer, so recursion makes no cycles at all.

Reference counting makes pointer updates part of memory management. Our instrumentation counts increments and decrements for the Job. A count reaching zero can trigger a cascade through a large object graph. Prompt reclamation therefore does not imply a small worst-case pause. Rust's Rc uses non-atomic counts; Arc supports sharing with atomic operations. Other runtimes have their own thread and ownership optimizations. Tracing trades per-update counting for graph walks and can reclaim cycles. Which trade wins depends on the workload, implementation and latency requirements; this one traffic count cannot settle it.

7Tracing: mark–sweep and mark–compactDegree2 min

Reference counting watches every pointer all the time. The other approach, which McCarthy used in the first LISP, does nothing until memory runs out, and then looks. Here is a heap, in address order, with two roots pointing in. Mark: start from the roots and follow every pointer, setting a mark bit in each object reached. A reaches F, C reaches H. B points at D, but nothing reaches B, so neither is marked. Sweep: walk the whole heap from one end to the other. Every object without a mark is garbage; its space goes onto a free list for future allocations. Notice the costs. Marking touches only the live objects. Sweeping touches every object, live or dead.

Sweeping has a second problem. After a sweep, the free space is scattered in holes between the live objects. Ask for five words: there are thirteen free, but no single hole bigger than three. The allocation fails, with memory to spare. This is fragmentation, the same problem Part 11's allocators fought. A tracing collector has an advantage those allocators never had: it knows every pointer, so it can move objects. Mark–compact slides the live objects down to one end, keeping their order, and rewrites every pointer to them. Now the free space is one block, and allocating is just bumping a pointer. The price is extra passes over the heap: the classic Lisp 2 algorithm takes three.

Run the same Job under four collectors with equal reserved heap capacity. The table counts words of marking, scanning or copying using each toy collector's stated work model. Mark-sweep leaves objects in place and can fragment free space. Compacting and copying move reachable objects and must update references. The generational layout reserves its nursery plus two old semispaces; Cheney reserves two equal semispaces. This comparison explains mechanisms on one workload, rather than crowning a universally best collector.

8Cheney's copying collector, and what it costsGraduate2 min

In 1970 C. J. Cheney found a collector that never looks at garbage at all. Split memory into two halves. The program allocates in one, from-space. Here a pair p holds a list of three cells; the roots point at p and at the middle cell; and three other objects are dead. To collect, copy each root's object into the empty half, to-space, and leave behind, in the old copy, a forwarding address: the new location. Now two pointers do all the work. Free marks the end of to-space. Scan walks through to-space, object by object. For every field that points into from-space, copy the target to free, unless it has already been forwarded, and update the field. When scan catches up with free, every live object has been copied, and nothing else has. The garbage was never touched. The halves swap roles, and the program continues in a heap that is perfectly compacted. Breadth-first, with no stack and no recursion: two pointers.

Count the words copied. A collection copies L live words and leaves S minus L words for new allocation in a semispace of size S. With a roughly stable live set, the copying work per allocated word is approximately L over S minus L. The solid curve measures the Job with different semispace sizes. Near the live set, collections are frequent. With more space, the finite run collects less often. The dashed estimate uses each run's mean sampled live set. Startup, end effects and changing liveness explain why it need not match exactly. This model counts copying, not root scans, allocation bookkeeping, or wall time. It explains a memory-versus-work trade within those assumptions; it is not a complete runtime cost theorem.

9GenerationsGraduate2 min

Can allocation ages guide collection? We record when each object is allocated and the last collection that observes it live. The histogram reports lower bounds on observed live age, measured in later words allocated. It does not record exact death times. Never observed at a collection does not mean dead: our three-cell result stays live at the end of a run with no collections, yet all three recorded ages are zero. The timeline shows this sampling gap. Objects reachable when measurement ends are end-censored. The displayed counts distinguish those cases. Many workloads do produce abundant short-lived objects, motivating generations. Treat that as an empirical hypothesis to test, not a universal law proved by this histogram.

Keep new objects in a nursery. A minor collection copies its reachable objects into old space. When old space may not fit another nursery, our full collection copies both regions together. It already empties the nursery, so there is no second, zero-work minor event. The table compares nursery sizes. Its percentage is promoted words divided by actual nursery words consumed in minor cycles, not a fraction of objects. The comparison below uses the same total reserved memory: nursery plus two old semispaces versus two Cheney semispaces. Work and pause columns count model words, not milliseconds. Generations are common, but not universal. Go's current collector, for example, is explicitly non-generational. Choose and measure the policy for the workload.

A young-only collection needs to know about older references into the nursery. If an old object stores a young pointer, scanning only roots and nursery objects would miss that edge. A write barrier records relevant stores in a remembered set or card table, which the minor collector scans as additional roots. Exact barriers vary by runtime. In our immutable core, fully initialized objects point only to values that already existed. Under this allocation and promotion model there are no old-to-young mutation edges, and measured barrier hits are zero. That removes this particular barrier requirement. Lazy updates, mutable fields and runtime bookkeeping can reintroduce it; immutability does not make every part of collection free.

10Collecting while the program runsGraduate3 min

Every collector so far stops the program while it works. For a large heap the pause can be a tenth of a second or more: too long for a game, a trading system, or a web server's tail latency. To collect a little at a time, we need to describe a collection half done. Dijkstra and his colleagues did it in 1978 with three colours. White: not reached yet. Gray: reached, but its fields not yet scanned. Black: reached and scanned. Marking shades the roots gray, then repeatedly takes a gray object, shades everything it points at, and makes it black. When nothing is gray, the white objects are garbage. Those steps can be interleaved with the program's own, or run on another core beside it. But then the program is changing pointers while the collector is following them.

Here is how it goes wrong. Marking is under way. The root and A are black, B is gray, C, which only B points at, is still white. Now the program runs. It copies B's pointer to C into A, which is already black. Then it deletes B's pointer to C. The collector resumes and scans B: nothing there. Marking ends with C white, so C is freed. But A, a live object, still points at it. The program will now read memory that belongs to someone else.

The loss needs two changes: a black object gains a white target, and the last gray-to-white path is cut. The strong invariant forbids black-to-white edges. The weak invariant permits them only when the white target is protected by a path of white objects from a gray object. In our insertion barrier, a black-source store shades a white target. Our deletion barrier shades the old white target before overwriting it. The three timelines apply these rules to the same pointer moves. The table summarizes two thousand randomized cycles, not a general concurrency proof. Our model also specifies root handling and allocates new objects black with a barrier; insertion mode rescans registers before finishing. Barriers add work and can retain floating garbage. The complete invariant includes these root and allocation rules, not just the field-store instruction.

Real runtimes expose different throughput and latency choices. Our allocation-heavy program uses sixty million allocations and two hundred thousand list heads. These are single runs on this host. The JVM runs use a fixed one-gibibyte heap. Serial and Parallel collect during pauses; G1 combines concurrent marking with stop-the-world phases. Read the measured pause counts and maxima here. ZGC performs much of its marking and relocation concurrently. Go marks concurrently but does not move objects, and its collector is non-generational. Go uses a growth target and a soft memory limit, so its heap policy differs from the JVM's. Short recorded pauses do not include all barrier, concurrent-worker or allocation-assist costs. The whole-run time is a second observation, not a universal ranking or a worst-case latency guarantee.

11Just-in-time compilersIndustry3 min

A JIT can use information gathered while a program runs. This installed V8 exposes Ignition, Sparkplug, Maglev and TurboFan configurations. Interpretation starts execution; later tiers trade compilation effort for more specialized code. Tier availability and policy vary with version and platform. The bars show Fibonacci of thirty-two with the stated tiers enabled, using the best of three runs. Enabling an extra tier need not make this short benchmark faster. The trace shows what this V8 actually compiled during a separate diagnostic run. Hotness predicts where compilation may pay off, but compilation, warmup, scheduling and speculation also cost time.

Property access can exploit repeated object structure. For getX, the runtime needs the location of x in the current object. An inline cache records a shape and an access strategy, guarding the fast path with a shape check. Polymorphic caches remember several cases. Megamorphic strategies handle more varied sites; their thresholds and lookup mechanisms depend on the engine. Our curve times twenty million four hundred and eighty thousand getX calls with one through thirty-two constructed shapes. The horizontal positions use a base-two logarithmic scale. The measured ratio is shown beside the graph.

What is a shape? In V8 it is a hidden class, called a map, and V8 can be asked about them directly. a and b were built with x and then y: same map, true. c has the same properties in the other order: a different map. And d got y later, by assignment: different again. A map records where each property lives, so an inline cache compares one map pointer instead of searching for a name. That is why JavaScript performance advice says: build your objects the same way every time. The engine is betting that you will.

Optimized code can depend on assumptions learned from earlier calls. Our add function first sees numbers and later receives strings. A type guard can fail, forcing the runtime to leave code that relied on the old assumption. The displayed trace comes from the installed Node and V8 version. Its actual bailout reasons and tier names are evidence for this run, not promises about every V8 release. Deoptimization reconstructs a state that less specialized code can continue from. The string call still returns a followed by b; correctness must survive a failed guess. The destination can be another tier, and further calls may be optimized again. Speculation trades guards, compilation and reconstruction work for faster common cases.

12Dynamic dispatch and exceptionsIndustry2 min

When s points to a shape, which area function runs? A common C++ ABI gives a polymorphic object a vptr leading to a table of method addresses. This diagram shows that implementation, rather than a language-mandated object layout. The virtual call reads the method address and calls through it. Compilers can remove this dispatch when they can prove the target. Our repaired benchmark deliberately disables devirtualization, uses opaque call boundaries and defined unsigned arithmetic, checks every checksum, and verifies an indirect call in the virtual loop's assembly. The table shows the best of three runs on this host. Loop overhead and branch prediction remain part of the measurement; the ordering is not a universal law.

A dispatch mechanism chooses code from runtime type information. Single dispatch uses the receiver's type. An interface may be implemented by unrelated concrete types, so a runtime needs an appropriate method mapping rather than assuming one universal class-table slot. JVM implementations use interface lookup and caching; Go interface values carry type-and-method information. These details are implementation choices. Multiple dispatch, as in Julia or CLOS, chooses using several argument types. Rust can monomorphize generic trait calls, but dyn trait objects dispatch dynamically. Haskell type-class dictionaries can also survive at runtime unless specialization removes them. Static types alone do not imply that every call has zero dispatch cost.

Exception implementations move costs to different paths. The table compares a plain call and a call that may throw, inside a handler, using our checked benchmark. Their measured times need not be identical. This platform uses table-driven unwinding: entering a try region does not register a handler dynamically. A throw searches metadata and unwinds frames. Zero-cost names this fast-path strategy, not zero code-size, optimization or cache cost. setjmp instead saves state on entry. This test measures that registration path; it does not time a longjmp. Throwing and constructing the exception has the displayed cost in this shallow example. The number depends on the exception, stack depth, ABI and machine, so use it as a measured case rather than a fixed ratio for all programs.

13WebAssembly, and other machinesIndustry3 min

WebAssembly is a typed virtual instruction set supported by major browsers. Our factorial uses a value stack: local.get pushes an argument and i64.mul consumes two integers. We assembled this module by hand and ran it in Node; the table shows the exact factorial-of-twenty result. Arithmetic uses WebAssembly's specified fixed-width rules. Control transfers target enclosing labels. For a block, branching exits at its end; for a loop, branching returns to its beginning. The two arrows show that essential difference. Structured control and declared types support validation, but a sandbox also relies on runtime bounds checks and the capabilities supplied through host imports.

Validation rejects malformed typed code before execution. The broken factorial reaches i64.mul with only one operand. Node's validator rejects it; the diagnostic shown here is the actual output of this installed version. The validator tracks operand types and control contexts, checking branch signatures and each instruction's stack effect. Structured code supports a linear pass under the validation model. Conrad Watt's 2018 work mechanized a specification, checker and interpreter in Isabelle, finding and correcting specification issues. Validation, runtime memory checks and host policy each contribute to isolation.

A runtime can search rather than just execute a function. These Prolog rules define append through the relationship among two input lists and their concatenation. Ask which X and Y concatenate to one, two, three. Our small engine searches and finds all four displayed splits. Resolution and backtracking explore alternatives, while unification matches terms and propagates variable bindings. Type inference also uses unification, but concrete algorithms differ: occurs checks, cyclic terms and type constructors need their own rules. The common idea connects logic programming with the type checker without making the two implementations identical.

Two more models deserve a mention. Actors, proposed by Carl Hewitt in 1973 and built into Erlang at Ericsson in 1986, are processes that share nothing and only send each other messages. Erlang's runtime runs millions of them, each with its own small heap, so each collects its own garbage without stopping the others. And its philosophy, let it crash, restarts failed processes from a supervisor, an idea Part 50 brings to distributed systems. In dataflow, an operation runs as soon as its inputs exist. A spreadsheet is a dataflow program, so is a TensorFlow graph, and so, inside, is Part 8's out-of-order core. Each runtime is an answer to the same question: what does it mean for a program to take a step?

14The Job, collectedGraduate2 min

Now price the complete Job on the Pebble VM. Each row is an actual passage executed by the emulator, with output checked against the reference. Instructions, allocations and copied words are exact for these executions. The no-collection comparison uses a large enough heap for the same passage. Subtracting instruction counts estimates collector instruction overhead, not the same fraction of elapsed time or out-of-order cycles. Cycles for larger projections use IPC from a smaller core sample. Keep measured emulator counts, sampled IPC and projected whole-corpus time distinct; none is a direct timing of thirty complete novels.

Row six adds a collected language runtime to our ledger. The hours and ratios are projections from the sampled passages and the stated core-pricing method. They are not a stopwatch measurement of the full corpus. The gap combines interpreter dispatch, data representation, algorithm choice and collection. It is a useful explanation target, but it cannot be attributed entirely to one mechanism or promised away by a JIT.

Where does the VM's extra work go? Dispatch interprets each bytecode using several Pebble instructions, and tagged heap structures add representation work. The underlying word-counting algorithm still scans an association list; the runtime has not removed its quadratic growth. The collector's displayed share is an instruction-count difference against a no-collection run. A faster collector can save only the work attributable to collection under that model. Part sixteen changes the algorithm itself, a different source of improvement.

15Frontier: the limits of runtimesResearch4 min

Memory can buy less collection work, but state the cost model. Our curve shows copied words per allocated word against reserved memory divided by a collection-sampled live-set estimate. It does not plot measured wall time. Hertz and Berger's 2005 study compared selected Java workloads with an oracle that freed objects just before they became unreachable, not at their semantic last access. For their historical Appel collector, five times the memory matched explicit management, three times was seventeen percent slower, and twice was about seventy percent slower. Those are scoped empirical results. A modern collector's memory-time bounds depend on its machine, root and object model, movement policy, and workload. Define those assumptions before comparing measurements or claiming a lower bound.

A measured maximum pause is not a real-time guarantee. Many short pauses close together can still prevent useful progress. Minimum mutator utilization asks how much program time is guaranteed in every window of a specified length. Metronome schedules collection to obtain utilization guarantees under its allocation and live-data assumptions. Earlier work by Blelloch and Cheng already gives explicit real-time copying bounds, including terms for reachable space, object count, processors and object depth. A vague three-way goal is therefore not one unsolved theorem. Meaningful research starts from an established bound and specifies what should improve: constants, root handling, object-size limits, scheduling, or a different machine model. Then prove or measure that particular extension.

Can we derive compiled code from an interpreter? Fix the source program and specialize an interpreter with respect to it. A suitable partial evaluator leaves a residual program that still accepts the runtime input. The diagram separates that fixed program from the input that remains unknown. Specializing the specializer with respect to the interpreter yields a compiler: the second Futamura projection. PyPy's meta-tracing takes a different route, tracing interpreter execution along hot paths. Truffle and Graal use interpreter partial evaluation with supporting annotations and runtime machinery. These methods can remove dispatch and expose optimization opportunities. They do not guarantee removal of all interpretation cost or recovery of our ledger's entire gap; representation and algorithms still matter.

Measurement needs more than one appealing run. The usual JIT story predicts a slow start followed by a stable compiled peak. Barrett and colleagues tested that story in 2017 with many iterations across seven virtual machines. Their benchmarks did not all reach a stable peak; some slowed down. Our best-of-three tables are small illustrations, not that kind of steady-state study. Correctness has strong starting points too: mechanized WebAssembly semantics and verified compiler and collector components in projects such as CakeML. Integrating those guarantees with a specified production JIT, concurrency model and native interface is a more precise research goal than claiming that no runtime has ever been verified.

Here are useful research directions with explicit scope. Start from a known real-time collector bound. State the machine, allocation rate, roots, object sizes and liveness limits, then seek a precise improvement or matching lower bound. Can interpreter-derived compilers provide useful performance guarantees for a defined class of programs? Can JIT performance be predicted across changing phases rather than summarized by a best run? How far can verified compilation and collection be integrated with production concurrency, native interfaces and optimizing JITs? Existing verified components provide starting points. This part's research exercise chooses the first direction and asks for a model, a baseline theorem and a testable extension.

Recap, problems, and where this comes backAll tracks3 min

We built an environment-based interpreter, closures and closure conversion. Continuations make pending work explicit; proper tail calls reuse frames in a tail-call chain, while other recursion may still grow the stack. We implemented bytecode on Pebble and cross-checked tested in-range executions. We ran tracing collectors on the Job and instrumented reference-count traffic. We distinguished collection-sampled ages from object death, then examined generations, tri-color invariants and barriers. Finally, measurements from this host illustrated JIT tiers, inline caches, deoptimization, dispatch, exceptions and WebAssembly. Each model explains a mechanism; each measurement keeps its own scope.

Where this comes back. Part 16 opens Act Four by changing the Job's algorithm, for ledger row seven. Part 31's kernel gives every thread its own stack, and Part 32's virtual memory sits under every heap. Part 33 returns to atomic operations and memory barriers, the hardware relatives of the write barriers here. Part 42 opens the browser, where V8 and WebAssembly live. Part 50 brings Erlang's supervisors to whole services. Parts 54 and 55 prove compilers and runtimes correct, and Part 58 asks what a program means.

In practice, profile the runtime and workload you actually use. Heap size, collector policy and pause targets express different tradeoffs. Allocation profiles reveal unnecessary objects; stable object layouts can help some JavaScript hot paths, but measure rather than assume. Lua and JavaScript are embedded in larger applications, while WebAssembly supports isolated plug-ins and services when the runtime checks and host capabilities are configured appropriately. The models in this part give you questions to ask and measurements to interpret.

The notes contain six exercises with worked solutions or starting points. Convert a closure, compare direct, CPS and accumulator sums, trace Cheney by hand, and derive two explicit collection cost models. The build exercise adds a nursery and measures its benefit under a stated instruction model. The research exercise starts from a known real-time collector bound: define the assumptions and propose one precise extension, rather than treating an underspecified three-way goal as an unsolved theorem.

Next time, Act Four begins. Seven rows of the ledger have made the machine faster, and the runtime more comfortable. The Job is still quadratic. Part 16 counts steps: merge sort and the master theorem, a lower bound on sorting that comes from information, and quicksort's average case, which is a small piece of calculus. Part 16, Counting Steps.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 16 opens Act IV by changing the Job's algorithm. Part 31's kernel gives every thread its own stack and Part 32's virtual memory sits under every heap; Part 33 returns to atomics and memory barriers, the hardware relatives of the write barriers here. Part 42 opens the browser, where V8 and WebAssembly live, Parts 54 and 55 prove compilers and runtimes correct, and Part 58 asks what a program means.

Key results

The part's results in one place, for revision.

A closure\(\displaystyle \langle \lambda x.\,e,\ \rho\rangle\ \text{applied }\allowbreak \text{to } v:\quad\allowbreak \operatorname{eval}\bigl(e,\ \rho[x\mapsto v]\bigr)\)
What a collector keeps\(\displaystyle \text{live}\ \subseteq\ \text{reachable }\allowbreak \text{from }\allowbreak \text{the }\allowbreak \text{roots}\ =\ \text{kept}\)
Copying cost\(\displaystyle \frac{\text{words copied}}{\text{words allocated}}\ \approx\ \frac{L}{S-L}\qquad\allowbreak (L \text{ live},\ S \text{ semispace})\)
Strong tri-colour invariant\(\displaystyle \text{no }\allowbreak \text{black }\allowbreak \text{object }\allowbreak \text{points }\allowbreak \text{to }\allowbreak \text{a }\allowbreak \text{white }\allowbreak \text{object}\)
Futamura projections\(\displaystyle \operatorname{spec}(\mathit{int},p)=\mathit{target},\qquad\allowbreak \operatorname{spec}(\operatorname{spec},\mathit{int})=\mathit{compiler}\)

Try it

Lab 15 · What a copying collector costs, and what a missing barrier loses

Compile the Job in the lambda core to bytecode, run it on the reference VM with Cheney's collector in semispaces from tight to roomy, and compare the words copied with the film's L / (S - L) per allocated word. Then let a mutator rewrite pointers during a tri-colour mark with no barrier, with Dijkstra's and with Yuasa's, and count the live objects the collector would have freed.

Figure produced by Lab 15: What a copying collector costs, and what a missing barrier loses
Produced by the lab below, seed 0, in 1.7 s.
python -m videos.cs.labs 15 needs numpy, scipy, matplotlib · download lab15.py · source on GitHub
text                          4,325 bytes, 105,192 words allocated (24.3 per byte)
semispace 30,000              10 collections, 212,454 words copied   (model (A - S) L / (S - L): 182,474)
semispace 34,000               6 collections, 128,679 words copied   (model (A - S) L / (S - L): 121,625)
semispace 38,000               5 collections, 100,632 words copied   (model (A - S) L / (S - L):  75,661)
semispace 44,000               3 collections,  65,136 words copied   (model (A - S) L / (S - L):  59,611)
semispace 52,000               2 collections,  46,395 words copied   (model (A - S) L / (S - L):  42,841)
semispace 64,000               2 collections,  38,181 words copied   (model (A - S) L / (S - L):  17,510)
semispace 80,000               1 collections,  19,980 words copied   (model (A - S) L / (S - L):   8,386)
no barrier                     82 of 200 cycles lose a live object, 19.1 dead objects kept per cycle
Dijkstra's insertion barrier    0 of 200 cycles lose a live object, 21.2 dead objects kept per cycle
Yuasa's deletion barrier        0 of 200 cycles lose a live object, 24.1 dead objects kept per cycle

Copying costs nothing for garbage and L words per collection for live data, so the price per allocated word falls as L / (S - L) when memory grows; a barrier trades a little floating garbage for never freeing an object the program can still reach.
The code (107 lines; it asserts its own result)
"""Lab 15: run the Job on the series' VM under Cheney's collector in semispaces of several sizes, and price the copying."""

from videos.coursekit import labs
import numpy as np

from explainer.cs.pebble import programs as PR
from explainer.cs.runtime import bytecode as B
from explainer.cs.runtime import tricolor as T
from explainer.cs.runtime import vm as V

TITLE = "What a copying collector costs, and what a missing barrier loses"
GOAL = ("Compile the Job in the lambda core to bytecode, run it on the reference VM with Cheney's collector in "
        "semispaces from tight to roomy, and compare the words copied with the film's L / (S - L) per allocated "
        "word. Then let a mutator rewrite pointers during a tri-colour mark with no barrier, with Dijkstra's and "
        "with Yuasa's, and count the live objects the collector would have freed.")
TASKS = [
    "Replace V.Cheney(S) by V.MarkSweep(2 * S) (the same total memory). Its work is marking plus sweeping the whole heap: where does it cost less than copying?",
    "Use V.Generational(4096, S) and compare the words it copies with Cheney's at the same S. What does the nursery save, and why?",
    "In T.trial set mut_per_step=1 and then 8. How does the share of unbarriered cycles that lose an object change with the mutator's speed?",
]
WORDS = ("it is a truth universally acknowledged that single man in possession of good fortune must be want wife "
         "however little known the feelings or views such may on his first entering neighbourhood this so well "
         "fixed minds surrounding families he considered rightful property some one other their daughters").split()
SIZES = (30000, 34000, 38000, 44000, 52000, 64000, 80000)  # semispace sizes, in words
CYCLES = 200  # marking cycles per barrier


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()
    text = " ".join(rng.choice(WORDS, 700)) + " "
    prog, tape = B.job_program(), PR.job_tape(text)
    want = PR.job_reference(tape)

    # 1. the same program in seven semispaces
    rows = []
    for S in SIZES:
        heap = V.Cheney(S)
        try:
            vm = V.VM(prog, heap, tape=tape).run()
        except V.OutOfMemory:
            continue  # the live data does not fit: no collector can run the Job here
        assert bytes(vm.output) == want, f"the Job printed something else in a semispace of {S}"
        log = heap.log
        A, n = heap.clock, len(log)
        work = sum(r["work"] for r in log)
        L = sum(r["live"] for r in log) / max(n, 1)
        rows.append(dict(S=S, n=n, log=log, A=A, work=work, L=L, film=A * L / (S - L) if n else 0.0,
                         model=(A - S) * L / (S - L) if n else 0.0,
                         slack=(S - log[-1]["live"]) / (A - S) if n else 0.0))
    assert len(rows) >= 5, "most of the semispaces should hold the live data"
    A = rows[0]["A"]
    lab.row("text", f"{len(text):,} bytes, {A:,} words allocated ({A / len(text):.1f} per byte)")
    for r in rows:
        lab.row(f"semispace {r['S']:,}", f"{r['n']:>2} collections, {r['work']:>7,} words copied   "
                                         f"(model (A - S) L / (S - L): {r['model']:>7,.0f})")
    work = [r["work"] for r in rows]
    assert all(a >= b for a, b in zip(work, work[1:])), "more memory should never mean more copying"
    # Every collection but the last is paid back by the S - live words allocated after it (the first S words are
    # free), so the copying is (A - S) L / (S - L) with L the mean live size, short by at most the last cycle.
    for r in rows:
        if r["n"]:
            assert 0.98 * r["model"] <= r["work"] <= 1.02 * r["model"] * (1 + r["slack"]), \
                f"semispace {r['S']}: copied {r['work']}, the model says {r['model']:.0f}"
    assert sum(r["n"] >= 5 for r in rows) >= 2, "the tight semispaces should collect many times"
    assert all(r["work"] <= 1.05 * r["film"] for r in rows if r["n"]), "the film's A L / (S - L) is an upper estimate"
    assert work[0] > 4 * work[-1], "a tight heap should cost several times a roomy one"

    # 2. marking while the program runs
    lost = {}
    for barrier in (None, "dijkstra", "yuasa"):
        trials = [T.trial(1000 * seed + s, barrier=barrier) for s in range(CYCLES)]
        lost[barrier] = (sum(1 for t in trials if t["lost"]), sum(t["floating"] for t in trials) / CYCLES)
    for barrier, name in ((None, "no barrier"), ("dijkstra", "Dijkstra's insertion barrier"), ("yuasa", "Yuasa's deletion barrier")):
        lab.row(name, f"{lost[barrier][0]:>3} of {CYCLES} cycles lose a live object, "
                      f"{lost[barrier][1]:.1f} dead objects kept per cycle")
    assert lost[None][0] > CYCLES // 10, "a hostile mutator should hide objects from an unbarriered collector"
    assert lost["dijkstra"][0] == 0 and lost["yuasa"][0] == 0, "a barrier must never lose a live object"
    lab.note = ("Copying costs nothing for garbage and L words per collection for live data, so the price per "
                "allocated word falls as L / (S - L) when memory grows; a barrier trades a little floating garbage "
                "for never freeing an object the program can still reach.")

    fig, ax = labs.figure(2, size=(11, 4.4))
    S = np.array([r["S"] for r in rows])
    ax[0].plot(S / 1000, [r["film"] / r["A"] for r in rows], color=labs.GREY, ls="--", label="L / (S - L)")
    ax[0].plot(S / 1000, [r["model"] / r["A"] for r in rows], color=labs.GOLD, label="(1 - S/A) L / (S - L)")
    ax[0].plot(S / 1000, [r["work"] / r["A"] for r in rows], "o", color=labs.BLUE, label="measured on the VM")
    ax[0].set(title="Cheney's collector: words copied per word allocated", xlabel="semispace S (thousand words)",
              ylabel="copied / allocated", ylim=(0, None))
    ax[0].legend()
    tight = rows[0]["log"]
    xs, ys, last, base = [0], [0], 0, 0
    for r in tight:  # fill to the collection, then drop to what survived it
        xs += [r["clock"], r["clock"]]
        ys += [base + r["clock"] - last, r["live"]]
        last, base = r["clock"], r["live"]
    xs.append(A)
    ys.append(base + A - last)
    ax[1].plot(np.array(xs) / 1000, np.array(ys) / 1000, color=labs.BLUE, label="words in use")
    ax[1].plot([r["clock"] / 1000 for r in tight], [r["live"] / 1000 for r in tight], "o", ms=4,
               color=labs.GREEN, label="live after a collection")
    ax[1].axhline(rows[0]["S"] / 1000, color=labs.RED, ls="--", lw=1, label=f"semispace: {rows[0]['S']:,} words")
    ax[1].set(title="The Job's heap in the tightest semispace", xlabel="words allocated so far (thousands)",
              ylabel="thousand words")
    ax[1].legend(loc="lower right")
    lab.fig = fig
    return lab

Now change it

  1. Replace V.Cheney(S) by V.MarkSweep(2 * S) (the same total memory). Its work is marking plus sweeping the whole heap: where does it cost less than copying?
  2. Use V.Generational(4096, S) and compare the words it copies with Cheney's at the same S. What does the nursery save, and why?
  3. In T.trial set mut_per_step=1 and then 8. How does the share of unbarriered cycles that lose an object change with the mutator's speed?

Problems, with solutions

Try each problem before opening its solution.

  1. Closure conversion. Closure-convert let twice f = let g = fun x -> f (f x) in g by hand: find the free variables, and write the CLOSURE and FREE code our compiler would emit.

    Solution

    twice has one parameter, f (slot 0). The inner function's only free variable is f, so twice pushes it and builds a closure with one captured value: LOCAL 0; CLOSURE g, 1 free; SETLOCAL 1; LOCAL 1; RET. Inside g (parameter x in slot 0), each use of f reads the closure: FREE 0 (the outer f), FREE 0, LOCAL 0, CALL 1 (the inner f x), then TAILCALL 1 for the outer call, which is in tail position. f is not a known function, so each call passes one argument. Our compiler emits exactly this (p.listing("twice")), and twice (fun y -> y + 1) 5 gives 7.

  2. Three sums. Rewrite sum over a list in CPS and with an accumulator; give each version's stack depth and heap use for n elements.

    Solution

    Direct sum (h :: t) = h + sum t keeps Θ(n) pending frames. CPS sum_k (h :: t) k = sum_k t (fun s -> k (h + s)) uses tail calls and O(1) stack, but allocates n continuation closures. In this VM each captures h and k: a header, code slot and two captures, so 4n words plus constant setup. sum_a (h :: t) acc = sum_a t (acc + h) uses O(1) stack and no extra heap objects beyond input/setup. “No extra heap” excludes the already built input, startup closures and host big-integer storage. The reported 4,002-word example is 4n + 2, not exactly 4n. Reassociation is valid in the exact-integer model; floating point or checked-overflow semantics require separate justification. CPS makes pending work explicit without requiring an associative operator.

  3. Cheney by hand. From-space holds, in address order, a pair p = (c1, 7); cells c1 = 1 :: c2, d1 = 9 :: d2, c2 = 2 :: c3, d2 = 8 :: [], c3 = 3 :: []; and a closure k capturing d1. The roots point at p and c2. Run Cheney's algorithm, giving the to-space order and every forwarding address.

    Solution

    Roots first, in order: p is copied to to-space address 0 (every object here is 3 words: a header and two fields), c2 to 3; forwarding addresses are written into their old copies. Scan p: its field c1 is not yet copied, so c1 goes to 6. Scan c2: c3 goes to 9. Scan c1: its tail c2 is already forwarded (to 3), so the field is just updated. Scan c3: nothing. Scan meets free at 12: done. To-space order p, c2, c1, c3; forwarding addresses p → 0, c2 → 3, c1 → 6, c3 → 9. d1, d2 and k are never touched. (cheney_trace in compute.py reproduces this.)

  4. Two cost models. Derive the work per allocated word of a copying collector and of mark–sweep, with live data L in the same total memory M; compare at M = 2L, 4L and 8L.

    Solution

    Copying uses two semispaces of M/2. Each collection copies L words and frees M/2 − L for allocation: L / (M/2 − L). Mark–sweep marks L words and sweeps all M, then frees M − L: (L + M) / (M − L) (taking marking and sweeping a word as equal). At M = 2L, copying cannot run at all (M/2 = L), while mark–sweep costs 3. At 4L: copying 1, mark–sweep 5/3. At 8L: copying 1/3, mark–sweep 9/7. Copying wins once memory is plentiful, because it never touches garbage; mark–sweep works in tight memory and never moves an object. The Job's measurements (cost) follow the copying curve.

  5. Build: a nursery for the Pebble VM. Give the Pebble VM a nursery, in the Pebble language, and measure the Job. Why does the λ-core need no write barrier?

    Solution

    Solution sketch. Reserve a nursery plus two old semispaces. A minor copies nursery survivors into old space; a major copies both reachable regions and already empties the nursery. Do not count a second zero-work minor afterward. Under this core's complete-initialization, immutable-field and promotion rules there are no old-to-young mutation edges. Adding mutable fields requires a remembered set/barrier; lazy or runtime updates need their own treatment. Compare equal total capacity, and report promoted words / actually consumed nursery words, not an object fraction.

    Measure the implemented Pebble nursery rather than turning reference-collector word savings into a guaranteed native speedup. If an instruction-cost model has fraction f attributable to collection and a measured new collector instruction ratio r, its conditional Amdahl speedup is 1/(1-f+f*r). Neither f nor r is automatically a wall-time fraction.

  6. ★ Research: extend a known real-time collector bound. State a machine, mutator, root, object-size, allocation-rate and liveness model. Choose an established result and formulate one precise improvement or a matching lower-bound question under those assumptions.

    Where to start. The Blelloch–Cheng 1999 author abstract already reports space 2(R(1+2/k)+N+5PD) and stops proportional to k nonblocking machine instructions: R is maximum reachable space, N maximum reachable object count, D maximum object depth, P processors, and k copying work per allocated location. These quantities matter; “bounded pause, constant-factor space, constant work” without a model is not one established unsolved theorem. Read the full construction before attempting a proof extension. Possible projects include measuring constants on a specified immutable-core collector, investigating a different root policy or scheduler, or proving a bound for a clearly delimited object/machine model. Distinguish experiments, conjectures and proven results.

Notes and sources

Glossary

运行时 runtime · 解释器 interpreter · 求值 / 应用 eval / apply · 元循环求值器 metacircular evaluator · 环境 environment · 词法作用域 / 动态作用域 lexical / dynamic scope · 闭包 closure · funarg 问题 funarg problem · 闭包转换 closure conversion · 扁平闭包 / 链式闭包 flat / linked closure · 续延 continuation · 续延传递风格 continuation-passing style (CPS) · 尾调用 tail call · call/cc · CEK 机 CEK machine · 字节码 bytecode · 虚拟机 virtual machine · 栈式机 / 寄存器机 stack / register machine · 分派 dispatch · 线索代码 threaded code · 标签字 tagged word · 部分应用 partial application · 垃圾回收 garbage collection · 根 root · 可达 reachable · 引用计数 reference counting · 延迟引用计数 deferred reference counting · 标记–清除 mark–sweep · 标记–压缩 mark–compact · 碎片 fragmentation · 复制收集器 copying collector · 半空间 semispace · 转发地址 forwarding address · 代际假说 generational hypothesis · 新生代 nursery · 晋升 promotion · 写屏障 write barrier · 记忆集 remembered set · 卡表 card marking · 三色标记 tri-color marking · 强 / 弱三色不变式 strong / weak tri-color invariant · 增量更新 incremental update · 起始快照 snapshot at the beginning · 浮动垃圾 floating garbage · 停顿 pause · 最小变异器利用率 minimum mutator utilization · 即时编译 just-in-time compilation · 分层编译 tiered compilation · 内联缓存 inline cache · 多态内联缓存 polymorphic inline cache · 隐藏类 hidden class · 推测 speculation · 去优化 deoptimization · 追踪 JIT tracing JIT · 虚函数表 vtable · 多分派 multiple dispatch · 零开销异常 zero-cost exceptions · WebAssembly · 验证 validation · 消解 resolution · 参与者 actor · 数据流 dataflow · 二村映射 Futamura projections · 预热 warmup

Sources

Canon. Books: Abelson & Sussman, Structure and Interpretation of Computer Programs, chapters 4–5; Friedman & Wand, Essentials of Programming Languages; Appel, Compiling with Continuations (1992); Jones, Hosking & Moss, The Garbage Collection Handbook; Smith & Nair, Virtual Machines; Nystrom, Crafting Interpreters.

Papers: McCarthy, "Recursive functions of symbolic expressions and their computation by machine" (1960); Collins, "A method for overlapping and erasure of lists" (1960); Landin, "The mechanical evaluation of expressions" (1964); Moses, "The function of FUNCTION in LISP" (1970); Cheney, "A nonrecursive list compacting algorithm" (1970); Bell, "Threaded code" (1973); Deutsch & Bobrow (1976); Steele, "Debunking the 'expensive procedure call' myth" (1977); Dijkstra, Lamport, Martin, Scholten & Steffens, "On-the-fly garbage collection: an exercise in cooperation" (1978); Lieberman & Hewitt, "A real-time garbage collector based on the lifetimes of objects" (1983); Ungar, "Generation scavenging" (1984); Deutsch & Schiffman, "Efficient implementation of the Smalltalk-80 system" (1984); Felleisen & Friedman, "Control operators, the SECD-machine, and the λ-calculus" (1986); Yuasa, "Real-time garbage collection on general-purpose machines" (1990); Hölzle, Chambers & Ungar, "Optimizing dynamically-typed object-oriented languages with polymorphic inline caches" (1991) and "Debugging optimized code with dynamic deoptimization" (1992); Shao & Appel, "Space-efficient closure representations" (1994); Ertl & Gregg, "The structure and performance of efficient interpreters" (2003); Ierusalimschy, de Figueiredo & Celes, "The implementation of Lua 5.0" (2005); Shi, Casey, Ertl & Gregg, "Virtual machine showdown: stack versus registers" (2008); Rohou, Swamy & Seznec, "Branch prediction and the performance of interpreters: don't trust folklore" (2015); Haas et al., "Bringing the web up to speed with WebAssembly" (2017); Watt, "Mechanising and verifying the WebAssembly specification" (2018).

Frontier. Hertz & Berger, "Quantifying the performance of garbage collection vs. explicit memory management" (2005); Bacon, Cheng & Rajan, "A real-time garbage collector with low overhead and consistent utilization" (2003); Blelloch & Cheng, "On bounding time and space for multiprocessor garbage collection" (1999); Bendersky & Petrank, "Space overhead bounds for dynamic memory management with partial compaction" (2011); Cohen & Petrank (2013); Futamura, "Partial evaluation of computation process" (1971); Bolz, Cuni, Fijałkowski & Rigo, "Tracing the meta-level: PyPy's tracing JIT compiler" (2009); Würthinger et al., "Practical partial evaluation for high-performance dynamic language runtimes" (2017); Barrett, Bolz-Tereick, Killick, Mount & Tratt, "Virtual machine warmup blows hot and cold" (2017); the CakeML project's verified garbage collector.

About this partfrom its README

Part 15 closes Act III of the sixty-one-part course (plan, syllabus). Build the machinery beneath functions: environments and closures, continuations, bytecode dispatch, allocation and collection. Then compare selected mechanisms with real runtimes on the current host. The instruments live in explainer/cs/runtime/; compute.py records the data and versions, and measurements.py defines auditable observation and benchmark protocols.

  • Opening: the Job allocates temporary lists and pairs. Its displayed live peak is a collection sample, not an every-instruction liveness maximum.
  • 1. Interpreters: eval/apply, environments and a metacircular evaluator. Fibonacci timings are best-of-three process-internal measurements, not a ranking of languages.
  • 2. Closures: lexical versus dynamic scope, escaping captures and closure conversion. Heap allocation is our implementation choice; scope and storage are distinct.
  • 3. Continuations: direct, CPS and accumulator factorials. Counts are logical reference-VM slots and exclude Python big-integer storage/time. Proper tail calls bound a tail-call chain; the Job's non-tail bump recursion still grows with vocabulary. call/cc changes control without undoing arbitrary effects.
  • 4. Bytecode: the stack instruction set, compiled bump, opcode mix, and stack versus register VMs. Pebble has 32-bit tagged words with a signed 31-bit integer payload; the Python VM uses unbounded integers.
  • 5. Pebble VM: actual source, tested in-range cosimulation, dispatch order and native C dispatch timing. Agreement on the examples supports finite implementation checks, not universal equivalence.
  • 6. Reference counting: reachability, zero-count cascades, cycles, and instrumented pointer-update traffic. A cascade can pause; Rust Rc is non-atomic whereas Arc supports sharing with atomics.
  • 7. Tracing: mark–sweep, fragmentation, compaction and four collectors with equal reserved capacity. Work columns use the stated model's word operations, which need not cost equal native time.
  • 8. Cheney: copying, actual forwarding locations, updated roots/fields and scan/free pointers. The approximation L/(S-L) counts copying, excluding root scans, bookkeeping and finite-run boundaries.
  • 9. Generations: last-observed-live ages and end censoring, an unobserved-but-live result witness, nursery sizes and actual promoted-word/consumed-word ratios. A major already empties the nursery.
  • 10. Concurrent collection: the same pointer moves under no, insertion and deletion barriers; root/allocation policies; randomized checks. JVM and Go pause logs use explicit, different heap policies.
  • 11. JITs: version-specific tiers, inline-cache measurements with an explicit logarithmic axis, hidden classes and actual deoptimization trace excerpts. An enabled tier need not improve a short run.
  • 12. Dispatch/exceptions: vtables and interface/multiple dispatch. The native benchmark uses defined unsigned arithmetic, checked results, opaque boundaries, disabled devirtualization and an assembly witness. Table-driven exceptions move costs off handler entry; they do not remove all metadata/optimization costs.
  • 13. Other machines: a hand-assembled WebAssembly module and actual validation failure. Branching to a block exits; branching to a loop restarts its header. Specification verification is separate from engine verification; isolation also needs runtime bounds checks and host policy. Prolog, actors and dataflow follow.
  • 14. The Job: exact emulator counts for six passages, sampled IPC and projected ledger row 6. Collector instruction share is not automatically the same fraction of wall time or cycles.
  • 15. Frontier: scoped historical memory/time results, established real-time bounds and precise extensions, fixed-program specialization, meta-tracing, warmup evidence and integration of verified runtime components.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Interpreters: SICP's eval/apply; McCarthy's eval and Russell's interpreter; metacircularity; fib(32) on every runtime on this machine (gcc, Go, HotSpot and -Xint, V8 and --jitless, CPython).
  2. Environments and closures; lexical against dynamic scope (both computed); the funarg problem (Moses 1970); closure conversion (CLOSURE, FREE); flat against linked closures.
  3. Continuations and CPS: the stack made explicit (CPS factorial on our VM); tail calls as jumps (the Job's stack with and without them); call/cc as an early exit on a CEK machine; exceptions and generators from continuations; Peirce's law.
  4. Bytecode VMs: our 36-instruction stack machine with tagged words; bump compiled; the opcode mix; CPython's dis; stack against register (Lua 5, Shi et al. 2008).
  5. The Pebble VM: the VM and Cheney's collector in the Pebble language, co-simulated with the reference count for count; 47 instructions per bytecode; dispatch order; switch against threaded code measured in C.
  6. Why garbage collection exists (McCarthy 1960): reachability. Reference counting (Collins 1960): the cascade; cycles, and CPython's cycle collector measured; what counting would cost the Job; deferred RC.
  7. Tracing collectors:
    • mark–sweep and mark–compact, animated; fragmentation; four collectors on the Job in the same memory;
    • Cheney's copying collector (1970), traced with its two pointers;
    • the cost model, work per allocated word ~ L/(S − L), measured against heap size.
  8. The generational hypothesis (Lieberman & Hewitt 1983, Ungar 1984), measured: 87% of the Job's objects never survive a collection; nurseries of six sizes; remembered sets and write barriers, and why the λ-core needs none.
  9. Incremental and concurrent GC: the tri-color invariant (Dijkstra et al. 1978), strong and weak; a lost object, move by move; Dijkstra's and Yuasa's barriers tested on 2,000 random cycles; pause times of the JVM's four collectors and Go's on this machine.
  10. JITs: V8's tiers measured; inline caches against the number of shapes (Deutsch & Schiffman 1984; Self's PICs); hidden classes; speculation and deoptimization traced (Hölzle 1992); tracing JITs.
  11. Dynamic dispatch: vtables measured, interfaces, multiple dispatch.
  12. Implementing exceptions: zero-cost tables against setjmp, measured.
  13. WebAssembly: a module assembled by hand and run by node; validation is type checking, and node's error.
  14. Other paradigms: Prolog as resolution and unification (append run backwards), actors (Erlang), dataflow.
  15. The Job in the λ-core, garbage-collected, on the Pebble VM: ledger row 6 (about 2.4 hours, 149× row 5; the collector under 4%). Frontier: memory against time (Hertz & Berger 2005); minimum mutator utilization and Metronome; the Futamura projections, PyPy and Truffle; warmup (Barrett et al. 2017); verified runtimes; open problems. Outro.

Computed: the λ-core compiled to bytecode and run by a reference VM under copying, mark–sweep, mark–compact and generational collectors (work, pauses, holes, lifetimes, nursery sizes); the same VM in the Pebble language on the emulator and on Part 8's core; reference-count traffic; tri-color marking under a hostile mutator; a CEK machine and a tiny Prolog; CPython, V8, HotSpot, Go, gcc and node timed and traced on this machine. Visuals: the heap filling and emptying; eval and apply; a closure capturing its environment; the stack as a chain of closures; the mark wavefront and the sweep; Cheney's scan and free pointers; the tri-color loss; tiers and inline caches as bars. In practice: the JVM, V8, CPython, .NET and the Go runtime; GC tuning (pause targets, heap sizing); allocation profiling; embedded interpreters; WebAssembly runtimes. Reading: Abelson & Sussman, SICP ch. 4–5; Friedman & Wand, Essentials of Programming Languages; Appel, Compiling with Continuations; Jones, Hosking & Moss, The Garbage Collection Handbook; Smith & Nair, Virtual Machines; Nystrom; Ierusalimschy et al. 2005; Hölzle et al. 1991–92; Haas et al. 2017; Hertz & Berger 2005.


中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 闭包转换。 手工对 let twice f = let g = fun x -> f (f x) in g 做闭包转换:找出自由变量,写出我们的编译器会生成的 CLOSURE 与 FREE 代码。

    解答

    twice 有一个参数 f(槽 0)。内层函数唯一的自由变量是 f,所以 twice 先把它压栈,再建一个捕获一个值的闭包: LOCAL 0; CLOSURE g, 1 free; SETLOCAL 1; LOCAL 1; RET。在 g 内部(参数 x 在槽 0),每次用到 f 都从闭包里读: FREE 0(外层的 f)、FREE 0、LOCAL 0、CALL 1(内层的 f x),然后外层调用处于尾位置,用 TAILCALL 1。 f 不是已知函数,所以每次调用只传一个参数。我们的编译器生成的正是这些(p.listing("twice")), twice (fun y -> y + 1) 5 得 7。

  2. 三种求和。 把列表上的 sum 改写成 CPS 形式和带累加器的形式;给出每个版本对 n 个元素的栈深度和堆用量。

    解答

    直接形式每个元素保留一个待做加法的帧,栈为 Θ(n)。CPS 用尾调用,栈为 O(1),但创建 n 个续延闭包; 在本虚拟机中,每个闭包有头、代码槽以及 h 和 k 两项捕获,共 4 个字,因此是 4n 加常数启动量。累加器版本使用 O(1) 栈, 除输入和启动对象外不再创建堆对象。“不再分配”不包含已有输入、启动闭包及宿主大整数存储。4,002 个字的例子是 4n + 2, 不恰好是 4n。精确整数模型允许加法重结合;浮点或检查溢出语义需要另外论证。CPS 显式保存待做工作,无须运算满足结合律。

  3. 手算切尼算法。 来源空间按地址顺序存放:序对 p = (c1, 7);单元 c1 = 1 :: c2、d1 = 9 :: d2、c2 = 2 :: c3、 d2 = 8 :: []、c3 = 3 :: [];以及捕获 d1 的闭包 k。根指向 p 和 c2。运行切尼算法,给出目标空间的顺序和每个转发地址。

    解答

    先按顺序处理根:p 复制到目标空间地址 0(这里每个对象 3 个字:一个头和两个字段),c2 复制到 3; 旧副本中写入转发地址。扫描 p:字段 c1 尚未复制,于是 c1 复制到 6。扫描 c2:c3 复制到 9。扫描 c1:它的尾 c2 已经转发(到 3),只需更新字段。扫描 c3:什么也没有。scan 追上 free(12):完成。目标空间顺序为 p、c2、c1、c3; 转发地址 p → 0、c2 → 3、c1 → 6、c3 → 9。d1、d2 和 k 从未被碰过。(compute.py 中的 cheney_trace 复现了这一过程。)

  4. 两个代价模型。 设活数据为 L,总内存同为 M,推导复制收集器与标记–清除每分配一个字的工作量;比较 M = 2L、 4L、8L 时的情形。

    解答

    复制收集器用两个 M/2 的半空间。每次收集复制 L 个字,并为分配腾出 M/2 − L:L / (M/2 − L)。标记–清除标记 L 个字,清扫全部 M,腾出 M − L:(L + M) / (M − L)(把标记一个字和清扫一个字看作同价)。M = 2L 时复制收集器根本 无法运行(M/2 = L),而标记–清除的代价是 3。4L 时:复制 1,标记–清除 5/3。8L 时:复制 1/3,标记–清除 9/7。 内存充裕时复制收集器胜出,因为它从不碰垃圾;标记–清除能在紧张的内存里工作,而且从不移动对象。作业的实测数据 (cost)符合复制收集器的曲线。

  5. 动手:给 Pebble 虚拟机加一个新生代。 用 Pebble 语言给 Pebble 虚拟机加一个新生代(nursery),并测量作业。 为什么 λ 核心不需要写屏障?

    解答

    解答要点。 预留新生代和两个老年代半空间。次收集把新生代存活对象复制到老年代;主收集复制两区中的可达对象, 已经清空新生代,不应再记录一次零工作的次收集。在这里的完整初始化、不可变字段和晋升规则下,没有老对象写入年轻指针的边。 增加可变字段时,需要记忆集和屏障;惰性及运行时更新也要单独处理。比较相等总容量,报告“晋升字数 / 实际消耗的新生代字数”, 不要把它称为对象比例。应当测量实际 Pebble 实现,不能把参考模型节省的字数直接当成保证的本机加速。 若指令代价模型中收集占比为 f,新收集器的实测指令比例为 r,则条件性的阿姆达尔加速为 1/(1-f+f*r);两者都不自动等于墙钟比例。

  6. ★ 研究:扩展一项已知实时收集器界。 说明机器、变异器、根、对象大小、分配速率和活数据模型,选择已有结果, 在这些假设下提出一项精确改进或匹配下界问题。

    从哪里开始。 布莱洛赫与程一九九九年的作者摘要 已给出空间界 2(R(1+2/k)+N+5PD),以及与 k 成正比的非阻塞机器指令停顿界。R 是最大可达空间,N 是最大可达对象数, D 是最大对象深度,P 是处理器数,k 是每分配一个位置所做的复制工作。这些量不能省略;没有模型的三项目标不是一个已确立的 未解决定理。尝试扩展证明前先阅读完整构造。可以测量指定不可变核心收集器的常数,研究不同的根策略或调度,或为明确限定的 对象和机器模型证明界。清楚区分实验、猜想和已经证明的结果。

Build the film

python -m videos.cs.cs15.compute        # the part's numbers, into .cache/cs15
python tools/build.py cs15                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs15 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs15. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs15.compute           # every number in the part (about ten minutes; the ledger item is most of it)
python tools/build.py cs15 -q l            # a 480p preview
python tools/build.py cs15                 # 1080p

interp, vm, rc, pauses, jit, dispatch and wasm run gcc, g++, java, go, node and CPython on this machine; their timings belong to the computer that runs them. Pebble instruction counts are exact for the executed examples; sampled IPC and whole-corpus runtime projections retain their stated assumptions. Native subprocess failures propagate rather than becoming cached timing text. Preserve or regenerate current schemas with --force cps tracing gen pauses dispatch jit after this correction.