Skip to content

Performance Tips

github-actions[bot] edited this page Dec 5, 2026 · 10 revisions

Performance Tips

Blinc is designed for high performance, but a few guidelines keep your UI on the compositor fast path: the codepath where a frame patches GPU primitives in place and re-dispatches only what changed, instead of re-walking and re-rasterising the tree.

For the architecture behind these tips, see GPU Rendering.

Stay on the fast path

The frame loop tries to short-circuit Phase 4 (paint) when nothing expensive changed since the last frame. The gates that have to hold:

  • No structural rebuild this frame.
  • No layout-affecting change (width, padding, gap, flex direction, …).
  • No scroll physics, bounds animation, or new overlay.
  • The render cache is valid.

If all gates hold, the compositor patches motion-bound and CSS-animated primitives in place and the GPU pass scissors a small damage rect. Tree size becomes irrelevant; work scales with what changed.

Anything that invalidates a gate forces a full walker rerun.

Patch Visual State in Place

Do: Let a stylesheet or a bound property carry hover, press and focus:

use blinc::core::reactive::computed;
use blinc::layout::prelude::*;

fn hover_button() -> impl ElementBuilder {
    let pointer = Interaction::keyed("hover-button");
    let hovered = pointer.hovered().signal();
    let bg = computed(move |g| {
        if g.get(hovered).unwrap_or(false) { Color::BLUE } else { Color::RED }
    });

    div()
        .track(&pointer)
        .bg(bg)
        .px(4.0)
        .py(2.0)
        .rounded(8.0)
        .child(text("Hover me").color(Color::WHITE))
}

Don't: Branch on a signal read to switch a visual property when CSS or a bound property (.bg(my_signal)) would do the job:

// AVOID: flipping this signal triggers a subtree rebuild because the
// branched expression rebuilds the element. Even when the compositor can
// patch the colour, the rebuild itself isn't free.
let is_hovered = ctx.use_signal(false);
div()
    .on_hover_enter(move |_| ctx.set(is_hovered, true))
    .on_hover_leave(move |_| ctx.set(is_hovered, false))
    .bg(if ctx.get(is_hovered).unwrap_or(false) {
        Color::BLUE
    } else {
        Color::RED
    })

Order of preference for visual state:

  1. CSS :hover / :focus / :active. Patched in place with no Rust code at all.
  2. A bound property or class (.bg(signal), .bg(computed), .class_when(name, signal)). Patched in place; nothing is rebuilt.
  3. stateful::<S>(). Rebuilds its subtree on every transition. Keep it for state machines whose states build different structure.
  4. Branched if/else driven by a signal read. Last resort; this rebuilds the reading component's subtree.

Minimize Signal Updates

A signal update re-runs the component that reads it, rebuilding that component's subtree (not the whole UI). Batch related updates so several mutations share a single rebuild:

// Good: single subtree rebuild
ctx.batch(|g| {
    g.set(x, 10);
    g.set(y, 20);
    g.set(z, 30);
});

// Avoid: three subtree rebuilds in succession
ctx.set(x, 10);
ctx.set(y, 20);
ctx.set(z, 30);

Note that signal binding (.bg(my_signal), .w(my_signal), etc.) is cheaper still: the compositor patches the GPU primitive directly without any subtree rebuild.

Use Keyed State Appropriately

Keyed state persists across rebuilds. Use it for:

  • Form input values
  • Toggle states
  • Selected items

Don't overuse; each key adds memory overhead.

Efficient List Rendering

A list that changes belongs in for_each. When the list changes, rows are added, removed and reordered in place; a row whose key stays keeps its element, and nothing around the list is rebuilt:

scroll()
    .h(500.0)
    .child(
        div()
            .flex_col()
            .for_each(items, |item: &Item| item.id, |item: Item| render_item(&item)),
    )

For large lists:

  1. Key by identity. A key that follows the item, not its position, lets a reorder move rows instead of rebuilding them.
  2. Cull or virtualize. Only render what is visible.
  3. Keep item cheap. It runs once per new key.

See Lists & Conditional Content.

Canvas Optimization

For custom drawing:

  1. Minimize state reads. Read animated values once, not per-shape.
  2. Use transforms. Push/pop transforms instead of recalculating positions.
  3. Batch similar draws. Group shapes by color/brush.
canvas(move |ctx, bounds| {
    // Read once
    let angle = timeline.lock().unwrap().get(entry_id).unwrap_or(0.0);

    // Use transform for rotation
    ctx.push_transform(Transform::rotate(angle));
    // ... draw ...
    ctx.pop_transform();
})

Animation Performance

  1. Use appropriate spring stiffness. Stiffer springs settle faster.
  2. Limit simultaneous animations. Too many can cause jank.
  3. Use timelines for loops. More efficient than many spring values.
// Good: single timeline with multiple entries
let timeline = ctx.use_animated_timeline();
let (x, y, scale) = timeline.lock().unwrap().configure(|t| {
    (t.add(0, 1000, 0.0, 100.0),
     t.add(0, 1000, 0.0, 100.0),
     t.add(0, 500, 1.0, 1.5))
});

A CSS keyframe animation of transform alone (translate, scale, rotate) on an element with no transform of its own is the cheapest kind, whatever its transform-origin: the element is painted once and the renderer moves it each frame, its text, images, SVG icons and nested animations included, with no texture held for it. An element with a clip-path polygon or path is moved the same way, its clip turning and moving with it, so a cn::spinner turns without painting again. So is a CSS transition of transform that scales uniformly, which may start and end on poses with a transform of their own (a card lifted on hover) and may change a solid background along the way (a button that shrinks and changes shade while pressed), and a keyframe animation or a transition of opacity on an element that paints a single filled rectangle: a solid background and no border, outline, shadow, children or effect, such as a skeleton placeholder. A transition begins with one full frame, and may end with one. A transition that changes a text or border colour, a shadow or anything else along with the transform is not moved that way, and neither is an element that paints more than a filled rectangle under a fade, because a fade has to treat its overlapping draws as one picture. Those are painted once into a texture and the compositor moves it each frame, or, where the subtree cannot be a texture, painted again every frame. A texture holds only while nothing in the subtree is drawn in a pass of its own. A subtree with text, an SVG or a canvas in it is painted with the animation applied on every frame, so the text moves, scales and fades with its container about its transform-origin. Fading siblings of that kind, a grid of cards with labels, share one offscreen atlas and are composited in one pass, so the cost of the grid does not grow by a few render passes per card. Cards against the edge of the window are in the atlas too, and a grid of equal cards that each fade by a motion binding is moved by rows like any other bound node.

The same holds inside an overlay. A dialog, sheet, drawer, toast, popover, tooltip, hover card or context menu that enters or leaves by its CSS rules is painted once, with its backdrop, and then moved and faded, apart from a full frame where one of its animations ends. A list drawn inline in the page, such as an open cn select, is still painted again on every frame while it animates.

While the only thing moving is a CSS animation of opacity or colour that repeats, an indeterminate progress bar or a skeleton, the window draws 30 frames a second, not the display's rate, and an idle window with one on screen costs about half what it did. A transform, a layout change, a clip reveal, a scroll or a rebuild draws at the display's rate as before. A frame that input asks for during an ambient animation can wait up to 33 ms.

Each animation step is capped, so after a long frame (a stall, a debugger pause) an animation slows down instead of jumping to its end.

Memory Management

  1. Clone Arc, not data. Use Arc::clone() for shared state.
  2. Drop unused state. Clean up keyed state when no longer needed.
  3. Avoid closures capturing large data. Clone only what's needed.
// Good: clone the Arc, not the data
let data = Arc::clone(&shared_data);

// Avoid: captures entire struct
let large_struct = expensive_struct.clone();
div().on_click(move |_| use_struct(&large_struct))

Lazy Loading for Images

For applications with many images (galleries, feeds, chat), use lazy loading to defer loading until images are visible:

// Images in a scrollable gallery
scroll()
    .h(600.0)
    .child(
        div()
            .flex_row()
            .flex_wrap()
            .gap(8.0)
            .child(
                image_urls.iter().map(|url| {
                    img(*url)
                        .lazy()  // Only loads when scrolled into view
                        .placeholder_color(Color::rgba(0.2, 0.2, 0.2, 1.0))
                        .w(150.0)
                        .h(150.0)
                        .cover()
                })
            )
    )

Benefits:

  • Reduced initial memory. Only visible images are loaded.
  • Faster startup. No waiting for off-screen images.
  • Automatic cleanup. LRU cache evicts old images.

In a window, an image is loaded on a worker thread: decoding, compression and upload do not hold up the frame that scrolls it into view. Its placeholder, or nothing, is drawn until it arrives, and the next frame draws it. Headless rendering loads images in the frame that needs them, so a snapshot has them.

Emoji images (emoji() and emoji_sized()) are automatically lazy-loaded. The ~180MB system emoji font is only loaded when emoji characters actually appear on screen.

What is not drawn

A scroll container culls what is outside it: a child that, with everything under it, lies outside the container's on-screen rect (plus a 200 px overscan band) emits zero primitives, text, SVGs and images included. It doesn't enter the static batch, the dynamic batch, or any damage rect, and it takes no pointer events. Animations on off-screen children still tick but don't request the next frame. A descendant that overflows its row into view keeps the row drawn.

A scroll container whose content is boxes, text, images, SVG icons, translucent or faded elements and canvases is painted once and moved by the renderer as it scrolls, so a scroll frame costs what a frame that only moves something does. A canvas in it is drawn again each frame where it was painted and moved with the rest; one whose drawing changes its number of shapes, or uses meshes or GPU passes, makes that frame a full paint. Elements with a transform of their own, and elements a motion binding moves, are moved with the container too, the binding's change on top of the scroll, and so are elements with a clip-path, stacks, nested scroll containers and images inside groups. A clip inside the container (a card's rounded corners, a nested scroll area's viewport) moves with the content while the container's own viewport stays. A container holding something fixed or sticky, or a CSS animation that is not moved by rows, is painted again on each frame it scrolls, and so is a frame where it holds a filled path (a chart's pie or donut). Half a second after a container stops scrolling, its content is painted back into the cached static layer, so a frame at rest draws only what still moves, such as a spinner.

Culling stops below anything that places its content apart from layout (a CSS or bound transform, a motion, a layout animation) and at fixed and sticky children. .viewport_cull(false) turns it off for one container.

A clip with no area draws nothing beneath it. A collapsible, accordion section or tree group builds its content the first time it opens and keeps it, so one never opened costs nothing and a closed one draws nothing. A tab that is not selected is not built at all, and show(when, ..) builds nothing while when is false.

On macOS a window that is fully covered by another, minimized or on another Space is not rendered at all: its frames are dropped until the OS reports it visible again, and the first frame after paints whatever changed meanwhile. Animations in it stop with it.

Avoid the slow path

These changes trip the compositor fast path and require a full walker run:

Trigger Why
Animating width, height, padding, gap, margin Triggers Taffy re-layout
Animating clip-path inset / circle radius Damage-rect path can't patch in place
Animating filter: blur(…) or backdrop-filter Out of scope for apply_css_deltas
Scrolling a container that is not moved by rows Cache invalidated by scroll offset
Overlay / dialog / sheet open or close Its content is added or removed, one frame
Stateful flips that change child structure Subtree rebuild
CSS animation on a subtree with text, SVG or canvas Painted every frame instead of baked

Prefer animating transform: translate / scale / rotate, opacity, background-color, border-*, corner-radius, box-shadow, and 3D rotations. These all patch in place.

Watch for canvas closures

Canvas draw closures are called every frame by design; that's the contract. A canvas inside a tree means that tree can't take the cache-blit-only fast path because the closure has to run to produce its primitives.

If your canvas's draw output doesn't actually change every frame, gate the expensive work inside the closure on a signal you control rather than recomputing geometry on every paint.

Debugging Performance

Enable tracing to identify bottlenecks:

tracing_subscriber::fmt()
    .with_env_filter("blinc_layout=debug")
    .init();

Look for:

  • did_rebuild=true or needs_relayout=true in frame_timing traces. These mean the fast path was skipped.
  • Frequent subtree rebuilds.
  • Long frame times.
  • Excessive state updates.

Tracing an animation frame by frame

BLINC_MOTION_TRACE=<file> appends one JSON object per frame to the file: the clock step the animations took, whether the frame was drawn and by which path, what asked for another frame, and the progress of every CSS animation, transition and motion still running. It finds an animation that stalls, skips or waits for input. Unset, it costs nothing.

cost_us gives what each phase of the frame took, in microseconds. For a frame whose p4 (render) is long, p4_done_us says where in it the time went: when the style and animation pass finished and when the paint did, measured from the start of the phase. What is left of p4 after render is presenting the frame.

On macOS a trace of a new window has one gap of a fraction of a second after the first frame. The window is waiting for the app to become active, and no event, a scheduled wake included, is delivered until it is. It is not a slow frame, and it does not recur.

BLINC_MOTION_TRACE=/tmp/motion.jsonl cargo run -p blinc_app_examples --example cn_demo --features cn

Finding a stall in the event loop

BLINC_STALL_WATCHDOG=<ms> watches the event loop of a desktop window. When the loop stays in one event longer than the limit, it logs what the loop was running and for how long, on the target blinc_platform_desktop::stall. It also logs a wake that came more than the limit after the loop went to sleep, which is how a stalled window server or a missed wake shows. On macOS, BLINC_STALL_SAMPLE=<n> takes up to n one second sample runs of the process after the first 15 seconds, so the stack says where the main thread was blocked. The watchdog logs a long idle sleep too, so read the times: a sleep with no input is not a stall. Unset, it costs nothing.

BLINC_STALL_WATCHDOG=100 BLINC_STALL_SAMPLE=3 RUST_LOG=warn cargo run -p blinc_app_examples --example cn_demo --features cn

Profiling without a window

WindowedContext::headless(width, height) builds a context with no window, for profiling, tests and exports. It has its own animation scheduler, overlay manager and element registry. The cn_profile example uses it to time cn_demo's build, a full paint and a tab switch offscreen; run it under a sampling profiler to see where a frame goes:

cargo run -p blinc_app_examples --example cn_profile --features cn --release
samply record target/release/examples/cn_profile

Summary

Do Don't
Prefer CSS :hover / :focus, then bound properties, then Stateful Branch on a signal read to flip a visual property
Animate transform, opacity, colours, radii, shadow Animate width / height / padding / gap
Put long content in a scroll(), which culls what is off screen Lay out thousands of children in a plain div that clips them
Use for_each keyed by identity for lists that change Rebuild a list's container to change one row
Batch signal updates Update signals one at a time
Use Arc::clone() Clone large data into closures
Use timelines for loops Create many spring values
Read animated values once Read repeatedly in draw loops
Gate expensive canvas work on a signal Recompute geometry every frame inside a canvas closure

Navigation

Getting Started

Migrating

Mobile Development

Example Gallery

Web Development

Core Concepts

Animation

Components

Component Library (blinc_cn)

Widgets

Canvas Kit

Advanced

Architecture

Contributing

Clone this wiki locally