Skip to content

Performance

Wybthon keeps fine-grained dependency tracking and a Virtual DOM that batches native mutations into one bridge crossing per flush. Python execution, serialization, bridge calls, native DOM work, and browser rendering have different costs. Measure the operation you intend to improve.

Start with startup

On a first visit, loading and initializing Pyodide takes most of a second even with a warm cache, before any Wybthon code runs. For most applications that wait matters more than anything else on this page.

  • Repeat visits restore a snapshot. After the first boot, the bootstrap builds a memory snapshot of a runtime with Wybthon imported and later visits restore it, so they're ready in about a tenth of the time (see Boot snapshots). It's on by default; builds with Pyodide packages or wheels don't use it.
  • Prerender the pages users land on. Server rendering puts their content on screen at first paint, and the page hydrates once Python is ready. The server writes HTML directly rather than mounting a DOM, so rendering on request is cheap too: a 1,000-row table renders in about 6 ms in CPython.
  • Ship bytecode. Build with the same Python version as the Pyodide runtime so the archives include precompiled bytecode and the browser doesn't compile Wybthon or your application at startup (see Deployment).
  • Let the build start downloads early. wyb build inlines the manifest into the page and emits preload hints for Pyodide's module and both archives, so the browser starts fetching them while the page parses instead of after the bootstrap runs.
  • Keep the first import small. Load routes and heavy components with lazy, and move rarely used code into explicit chunks.

Production builds also turn dev mode off, so they skip the development checks and warnings.

What the engine does for you

Rendering cost in Wybthon is mostly Python bookkeeping, not browser DOM work, so the engine's fast paths target the Python side.

  • Templates are compiled ahead of time. Wybthon's compiler parses and validates each html(t"...") literal when its module is compiled, and writes the literal's parse tree and mount functions into the module as ordinary Python. It also replaces the call, so an instance is the literal's entry given a tuple of values: no t-string is built and nothing is parsed per instance. wyb build turns that into bytecode with the rest of your app, so a production build never parses a template or generates code at run time. On first use, a template rebuilds its slot plan from the stored tree. The static markup becomes a native <template>, and each instance mounts with one fused CLONE command that clones it, fills its text slots, marks its delegated listeners, and inserts it. The kernel registers only the nodes Python can address (the root, slot nodes, and handler nodes). No VNode tree is built for static parts. See Templates.
  • Bindings that read nothing cost nothing. The compiler's rule is syntactic, so {item["label"]} or a component parameter such as {title} becomes a getter even when it reads nothing reactive. Before allocating a computation, the renderer runs such an expression (one that makes no calls) under a lightweight probe. If it reads nothing reactive, the value is applied and no computation exists; if it returns an accessor without reading it, the binding targets that accessor directly. Any other hole or attribute binding that finishes its first run without reading anything reactive (and without creating children, cleanups, or async work) is disposed immediately, keeping only the DOM it produced.
  • Bindings are made in one step. A hole, a text slot, or an attribute binding is a small computation whose apply stage is a module function and whose data is its node id. It's built, run, and applied by one straight-line routine; the general scheduler takes over only while a transition, an action, a server render, or an unpublished preparation is involved. Fields only effects and async work use live in a separate record, and a computation that reads one source (or a source with one reader) links to it directly instead of through a dictionary. A node with one delegated handler stores it directly in the handler table.
  • SVG and MathML clone too. A template containing <svg> or <math>, or mounted under an SVG parent (a component that returns a <circle>), clones like any other: the kernel parses it inside a wrapper of that namespace. Only an SVG name whose capitals the HTML parser wouldn't restore (outside the specification's list, such as a custom dataPoint attribute) makes a template mount node by node.
  • Text slots stay text. A child slot whose expression returns text writes it into the slot's placeholder, filling the clone command on the first run. It becomes a hole region, able to hold nodes, only if the expression ever returns something other than text.
  • Disposal frees memory at once. Unmounting breaks every reference cycle the engine creates (a row and its node, a hole and its binding, a region and its node), so a removed subtree is freed by reference counting immediately instead of waiting for Python's cycle collector. Fewer live objects, and no cyclic garbage, mean less work for the collector, which matters most in Pyodide.
  • The collector runs when the page is idle. A flush or mount pauses Python's cyclic garbage collector, as allocating thousands of long-lived nodes would otherwise trigger collections in the middle of the work. In the browser, the collection that the paused work owes runs from requestIdleCallback, after the committed DOM has painted, and large disposals are freed there too, instead of inside the event handler that caused them.
  • Components mount straight into their slot. A component tag in a template builds its node directly, runs its body once under one owner, and mounts the template it returns in front of the slot's placeholder: one clone command for the component and one for its children, with no hole region, fragment, or markers of its own. In a template that's never re-rendered (a component's output, a list row), a child slot holding a list of one node mounts that node without a fragment; a component that returns a list, its children included, still mounts it as a fragment between two markers. Natively, a list row that's a component costs about twice the same markup inlined, where it used to cost three times as much and six times the commands (see engine-v9.md).
  • Constant props are free. A component can only receive new props when a reactive hole re-renders a tree that contains it (or render runs again into the same container). Everywhere else (another component's output, a list row, a Show branch, a template slot), a prop passed as a constant subscribes to nothing, and a prop passed as an expression subscribes the reader to what that expression reads.
  • Native control flow. Show, For, Repeat, and Switch mount as regions the reconciler manages directly, with no component, props object, or wrapper memo. One that fills a slot or a hole by itself ends at the slot's placeholder, so it creates no DOM nodes of its own. When a hole re-renders one of them, the new condition or source is pushed into the mounted region instead of remounting it.
  • Hidden branches cost nothing. The compiler makes the content and fallback of Show, Match, Switch, Loading, Errored, and client_only lazy when they're written as markup or a component call, so a branch's markup and components are built only when it shows. A Show whose condition is false, a Match that doesn't match, and a fallback that never appears create no nodes, owners, or computations. See Lazy branches.
  • Hydration costs what a clone does. A server-rendered template instance is claimed with one command, as a client render clones it with one; only slots that hold nodes add a command each. See Server rendering.
  • Probes learn. A template expression that read something reactive once ({row["label"]} over a store) isn't probed again for later instances of the template: its bindings become computations at once, instead of reading the field twice.
  • Rows are cheap. A list row is its own owner and its own index accessor. Its index is a plain integer until something reads index() in a tracking scope; only then is a signal created for it, so a row that never reads its index allocates nothing for it.
  • Keyed matching skips what didn't change. Matching a new list against the mounted rows first skips the common prefix and suffix by identity, without calling into each row. A replacement that only swapped two rows is detected the way Solid's reconcileArrays detects it, and becomes two native moves. Only what's left goes through a key table.
  • Native disposal. Removing a range or a subtree releases every node inside it in the JavaScript kernel, which walks the removed nodes natively. Python releases its own registrations (handlers, reactive bindings, refs) without visiting every node. Clearing a For list is one range removal plus disposal of each row's owner; when the list is all its parent holds, the kernel empties the parent at once.
  • Bulk replacement. When a keyed list reuses none of its rows, the old rows go in one DISPOSE_RANGE command and the new rows mount as one splice, instead of reconciling every unrelated pair.
  • Text placeholders. A hole whose neighbors aren't text uses a text-node placeholder, so a text result is a plain nodeValue write rather than a node replacement.
  • Lighter computations. Async state lives outside each computation until a computation actually runs async work, so an ordinary render binding doesn't allocate it.
  • Stores wrap lazily. Creating a store takes constant time, whatever its size: a nested dict, list, or dataclass gets its reactive bookkeeping the first time something reads it, and a field gets a subscription only when it's read in a tracking scope. A setter copies each container it edits once and publishes the changed fields with that container's commit. Natively, a store field write costs about 2.8 times a signal write; most of that is the draft views and the copy of the edited container. In the browser benchmark, store mode creates, updates, and appends rows 17% to 32% faster than Engine v6 did (see engine-v7.md).

Templates and h()

Templates and h share one set of prop appliers, so they behave the same; they differ in what happens before mounting.

  • A template is prepared by the compiler. Each call costs a cached lookup and one clone, and its structure is fixed by the literal.
  • An h() tree is built as VNodes on every call and mounts on the generic path, with no template to clone.

Use templates for markup you write by hand, and especially for list rows. Use h() where markup is built by code.

Use the incremental paths

  • Bind values where they're shown. Write the read where it's used (<b title={role()}>{name()}</b>), and only that attribute or text node updates. A hole that returns a subtree re-runs as a whole: a template from the same literal is patched slot by slot, but anything else is rebuilt. A plain function called in markup ({user_card(user())}) is such a hole, so make it a component instead: {UserCard(name=user().name)} mounts once and receives a getter, so a change updates only the text that reads its name parameter.
  • Keep holes small. A hole around a single text node patches one node.
  • Pass a store list directly to For. Local draft edits can use its change records. A list comprehension creates a replacement list that needs generic matching.
  • Use a shallow store for data you replace wholesale. create_store(initial, shallow=True) makes only the top level reactive, so a large value under it, such as an API response, is stored as plain data and never wrapped. Replace it to change it.
  • Select rows with a projection. Each row reads its own key, so a selection change notifies only the old and new rows, not every row:

    from wybthon import For, component, create_projection, create_signal, html
    
    
    @component
    def Rows():
        rows, set_rows = create_signal([{"id": i, "label": f"Row {i}"} for i in range(1000)])
        selected, set_selected = create_signal(None)
        is_selected = create_projection(lambda: {} if selected() is None else {selected(): True})
    
        def row(item, index):
            def select():
                set_selected(item["id"])
    
            return html(t"""
              <li class={"danger" if is_selected.get(item["id"]) else ""} onclick={select}>{item["label"]}</li>
            """)
    
        return html(t"<ul>{For(rows, row)}</ul>")
    

    is_selected.get(key) is tracked per key and returns None when the key is absent. Each row mounts with one clone command, and a selection change sends one command per affected row.

  • Use Repeat(count, row) for integer slots. Growing it mounts only the new slots.

  • Keep component setup stable. Place dynamic reads in the markup, memos, or effects. Components don't rerun for ordinary state updates.
  • Virtualize large collections. Use VirtualFor for large scrollable collections with fixed row heights. Offscreen rows are disposed, so store durable row state outside the row component.
from wybthon import create_signal, html
from wybthon.virtual import VirtualFor

records, set_records = create_signal([{"name": f"Record {i}"} for i in range(10_000)])


def record(item, index):
    return html(t"<p>{item['name']}</p>")


VirtualFor(records, record, row_height=32, height=400, overscan=4)

map_cooperative(items, fn, budget_ms=8) from wybthon.scheduling yields between chunks of expensive Python work, and yield_to_browser() provides an explicit cooperative yield. A single expensive callback still blocks until it returns; these helpers don't preempt Python or replace a worker.

Measure work as well as time

from wybthon import create_root, create_store, flush
from wybthon.diagnostics import profile, runtime_stats

store, edit = create_root(lambda dispose: create_store({"rows": []}))

with profile() as measured:
    edit(lambda draft: draft["rows"].append({"id": 1}))
    flush()
print(measured.as_dict())
print(runtime_stats())

Profiling is opt-in. Reports include computation runs, rows created, list entries scanned, edit records, commits, DOM commands, serialized bytes, and serialization and kernel time when those operations occur. template_clones counts template instances mounted by cloning. inspect_graph(owner) reports ownership and dependencies without evaluating values.

The repository's benchmarks/check_work.py gates command counts in CI: appending 1,000 rows must create 1,000 rows with one template clone command each, and selection and swap must each emit at most two commands. Work counts are deterministic, so they make better regression gates than timings.

Benchmarks

uv sync --locked --group dev
uv run playwright install chromium
uv run python benchmarks/browser_bench.py --mode signal --json
uv run python benchmarks/browser_bench.py --mode store --json

The browser benchmark builds the benchmark app (an ordinary project in benchmarks/app) with wyb build, serves it, and drives ordinary delegated button events. Each scenario restores its own baseline, warms up, checks that the DOM actually changed, and reports separate synchronous commit and input-to-frame samples. Append starts from 10,000 rows and verifies 11,000 afterward. Selection toggles between distinct rows.

Run comparisons serially on the same browser, runtime, hardware, and cache conditions. Use repeated samples and operation counts; don't turn a single local timing into a universal threshold. CI gates deterministic work contracts and saves browser measurements as artifacts. Production startup is measured separately by the generated loader.

benchmarks/compare_browser.py --baseline /path/to/baseline alternates identical operations between isolated checkouts, building each one, with five measured samples by default. It measures direct Python operations separately from delegated event dispatch. Use --mode store for store comparisons and --profile for additional, untimed CPU profiles.

benchmarks/row_bench.py times the same table operations in plain CPython against any checkout's sources, reporting Python's share of the work and the commands each operation sends. With the compiler, its rows are compiled the way an application's modules are, with no hand-written lambdas.

Recorded measurements, with the hardware and versions they were taken on, live in benchmarks/results/; engine-v4.md and engine-v3.md cover the engines before it. engine-v5.md measures Engine v5, which made creating rows about twice as fast natively as Engine v4, and engine-v7.md measures Engine v7's lazily wrapped stores.

A setter that edits a store list copies that list once, so a swap or splice in a long list costs a copy of the list. Arbitrary replacement lists still require linear matching. Removing a row shifts following indices. Virtualization is the appropriate tool when mounting the entire collection is the dominant cost.

Diagnose pending publication

Use diagnostics.inspect_transitions() to see which computations and actions hold each dependency group. diagnostics.inspect_graph(owner) includes read modes, group IDs, and provisional owners. An ordinary consumer of two pending results joins their groups; a separate latest() or is_pending() binding can publish during the hold. See Runtime contracts for the read and ownership rules.

A transition that remains open retains the values and resources still used by the visible UI. Dispose unused scopes and ensure application actions can finish or be canceled. The native async benchmark reports independent publication at increasing widths; its times exclude browser and network costs.