← Runtimes
Runtimes

Rust monomorphization and trait dispatch

Copies per type, or one function and a table.

Generic specialization uses compile-time type information; dynamic dispatch selects an implementation through runtime value information.

Outcome

Predict how many instances a generic function produces in each language, follow instantiation through generic call chains, and explain what dynamic dispatch adds to a value.

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

Monomorphization
Creating concrete instantiations from generic code before later optimization and linking.
Instance
A generic function specialization for particular type arguments; the planner records its logical demand.
Dynamic dispatch
Selecting an implementation using runtime value/type information; a trait object’s vtable is one mechanism.
Vtable
A table of function pointers for one type’s implementation of a trait or interface.
Template instantiation
In C++, generating a function or class from a template for given arguments.

Where a generic call becomes concrete

A generic definition describes operations over type parameters. Monomorphization creates concrete instantiations for selected type arguments; calls from those bodies can demand further instances. An instance is a compilation demand, so its presence does not promise a separate final machine-code body after optimization and linking.

Dynamic dispatch lets a caller use a common abstraction while the selected value supplies the implementation. This joins generic programming with runtime representation: choose which type choices are fixed at compilation and which remain open when values arrive. Rust trait objects, Go interfaces, C++ virtual objects and JavaScript prototype lookup carry that choice differently; neither symbol counts nor representation sizes alone measure the performance trade-off.

01Instantiation

How many copies of a generic function exist?

A shipping service reuses its largest helper for parcel weights, fuel surcharges and pickup dates. The build team wants to know what extra compilation those uses demand before replacing the carrier-rule abstraction. They need to distinguish logical specialization requests, the symbols a build retained, and calls selected from runtime configuration.

The shipment’s weights, surcharge percentages and fixed-format pickup dates use the same largest source helper. Its type argument is known at each call site. TypeScript erases that parameter; Rust/C++ start from concrete instantiations; the documented Go gc-toolchain strategy can share by GC-shape group with type dictionaries. The retained symbol listing shows one build’s outcome of those strategies.

largest is a function template; each new T instantiates it.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// One generic helper used on a shipment: weights in grams, surcharge percentages,
// pickup dates.

#include <iostream>
#include <string_view>
#include <vector>

template <typename T> T largest(const std::vector<T> &items) {
    T best = items[0];

    for (const T &item : items) {
        if (item > best) {
            best = item;
        }
    }

    return best;
}

int main() {
    using namespace std::literals;

    std::cout << largest(std::vector{1200, 5400, 800}) << ' '
              << largest(std::vector{4.5, 7.25}) << ' '
              << largest(std::vector{"2026-10-30"sv, "2026-11-02"sv}) << '\n';
}
The retained clang++ -O0 artifact prints 5400 7.25 2026-11-02. Which largest instantiations did its recorded symbol listing contain?
C++ · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
g++ -std=c++23 -Wall -Wextra main.cpp -o main && ./main

Predictions about symbols and sizes refer to retained macOS arm64 artifacts, read with nm/go tool nm. The symbol record names rustc 1.86.0 opt-level 0/v0, Apple clang 17 -O0 and Go 1.27.3; separate runtime receipts retain their own versions. Current formatted source bytes have not been rerun natively. Optimizers/linkers can inline, discard, merge or devirtualize code, and representation sizes depend on target/ABI. TypeScript’s command explicitly emits ES2022 JavaScript.

02Dynamic dispatch

What does calling through a trait or interface cost?

Carrier configuration can select an implementation through a trait/interface or virtual base. Such abstractions can carry information for runtime method selection, while optimizers may remove an indirect call when the concrete value is known. Here we compare representation and semantic dispatch paths, without measuring call latency.

The reduced probe constructs one PerKg directly and places it behind the abstraction; it does not load a carrier configuration. That keeps the representation question inspectable. The object’s known concrete type also makes devirtualization possible, so its output cannot prove an actual table-load instruction sequence.

The selected simple Itanium-ABI PerKg representation places its vptr inside the object; C++ itself does not prescribe that layout.

main.cpp
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// A carrier's rate rule with and without a virtual function.

#include <cstdint>
#include <iostream>

struct PlainPerKg {
    std::int64_t cents;
    std::int64_t quote(std::int64_t kg) const {
        return cents * kg;
    }
};

struct RateRule {
    virtual ~RateRule() = default;
    virtual std::int64_t quote(std::int64_t kg) const = 0;
};

struct PerKg : RateRule {
    std::int64_t cents;
    explicit PerKg(std::int64_t c) : cents(c) {}
    std::int64_t quote(std::int64_t kg) const override {
        return cents * kg;
    }
};

int main() {
    const PerKg rate(450);
    const RateRule &rule = rate;

    std::cout << "quote: " << rule.quote(2) << '\n';
    std::cout << "PlainPerKg: " << sizeof(PlainPerKg)
              << " bytes, PerKg: " << sizeof(PerKg) << " bytes\n";
}
What did the retained arm64 Itanium-ABI C++ build print on its second line?

03Trade-off

What does specializing every use cost?

Concrete instantiation exposes type-specific operations to optimization and creates compilation demand. Final code size depends on what remains after optimization/linking; dynamic dispatch trades some static specialization for a common entry shape. To plan a comparison, the lab follows declared same-type generic calls through a finite graph rather than estimating actual bytes or performance.

For this trade-off model, forty distinct types request one generic helper each. Assume every specialized body is retained separately and entry calls are statically resolved. What cost and benefit does specialization model?

04Practice

Finish the instantiation planner

The build team uses an authored instantiation planner to report demands before choosing a quote-library policy. It lists function/type pairs, follows declared same-type dependencies, then separates shared handle bodies from exact-type dictionary records. The order is a report contract; no compiler, linker, machine-code count or binary-size measurement is performed.

The instantiation planner

One instance per type, instantiate what instances call, then share code between pointer types.

  1. easy · R-MONO-V4-1 One instance per type
  2. medium · R-MONO-V4-2 Instantiate what instances call
  3. hard · R-MONO-V4-3 Share code between pointer types
In the frontend A generic rate component is not a Rust specialization Optional

The quote screen uses this component with several rate-record types. Do those type arguments request separate Rust-style machine-code bodies from TypeScript?

The type relationship is checked before emission. It adds neither a runtime type validator nor a distinct component implementation for each rate type.

components/RateText.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export function RateText<Rate extends { cents: number }>({ rate }: { rate: Rate }) {
  return <span>{rate.cents}</span>;
}

The generic parameter constrains props during checking, then disappears from the emitted component. Framework bundling may produce server/client variants for other reasons; the supplied Rate argument itself does not trigger per-type specialization.

Sources: TypeScript: Generic types,Svelte: Generic props.

Sources

Sign in to keep your read marks on every device. Sign in

Was this helpful?

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.