Writing fast interfaces
Guidelines for state, lists, styling, text, drawing and resizing, each with the reason it keeps frames cheap.
A zgui frame does work in proportion to what changed, so most interfaces are fast without special effort. The guidelines below keep them fast as they grow. Each says what to do and why it helps; the cost model has the measured numbers behind them.
State
Give each row its own signal
Keep per-row state in the row's data as a signal, not in the collection:
#[derive(Clone, Debug)]
struct Todo {
id: u64,
label: String,
done: RwSignal<bool>, // the row's own state, not the list's
}
view! {
for item in move || items.get(), key = |item: &Todo| item.id {
row(
class = "todo",
class:done = move || item.done.get(),
on:click = move |_| item.done.update(|done| *done = !*done)
) {
text {{item.label.clone()}}
}
}
}Why: ticking an item writes only that item's done, so one class binding runs and the list does
nothing. If done lived in the collection, every tick would re-run the collection closure, clone
every key and diff the whole list.
A row that reads the collection to find itself subscribes to the whole collection again. Pass the
row its value, or a store Field, and read that.
Use a Selector for the selected item
use zgui::reactive::Selector;
let selected = RwSignal::new(0_u64);
let selector = Selector::new(move || selected.get());
view! {
for item in move || items.get(), key = |item: &Todo| item.id {
row(
class = "todo",
class:selected = move || selector.is_selected(&item.id),
on:click = move |_| selected.set(item.id)
) {
text {{item.label.clone()}}
}
}
}Why: if every row reads a plain selected signal, moving the selection re-runs every row. A
Selector keeps one small signal per watched key, so only two rows re-run: the one that lost the
selection and the one that gained it. See Stores and selectors.
Read the narrowest field
| A hole reads | It re-runs on |
|---|---|
Store<Settings> | every write to every field |
store.rows() | every write to every row |
store.rows().at_key(id).value() | writes to that one field of that one row |
Field<u32> | writes to the field the handle names |
Why: a hole re-runs on every write to what it read, including writes to anything below it. A plain signal that holds a struct behaves like the store root: every reader re-runs when any part changes.
Use if for structure and closure holes for values
// Compares the boolean. Adding a row to a list that already had rows swaps nothing.
if move || items.get().is_empty() {
label(class = "empty") {"Nothing to do yet."}
} else {
column(class = "list") { … }
}| What you are choosing between | Use | What is compared |
|---|---|---|
| two branches, known in advance | if | the boolean |
| several branches of different view types | Dynamic | the view type; the same type updates in place |
| no branches; the hole produces a value | a closure hole | for text, the string it writes |
Why: if swaps only when its answer changes. A closure hole that returns a subtree rebuilds it
whenever anything it read changes. A rebuild runs cleanups, restarts timers and loses state such as
a scroll position or a half-typed field.
Add a memo only where readers share a result
| Situation | Memo? |
|---|---|
| several holes or rows read one derived value | yes: one computation instead of one each |
| the result is narrower than its inputs, and the reader rebuilds a subtree | yes: the reader re-runs only when the result changes |
| one reader, and it is a text hole | no: the text node already compares |
an if condition | no: if already compares |
a.get() + b.get() | no: the bookkeeping costs more than the addition |
a large Vec or String that is cheap to rebuild | no: every run pays a full comparison |
Why: a memo runs once per flush however many readers it has, and notifies them only when its value changes. Where neither of those saves anything, it is pure overhead.
You do not need a memo to batch writes. A signal written a thousand times between two flushes causes one re-run, not a thousand.
Lists
Key every list by a stable ID
view! {
column(class = "list") {
for item in move || items.get(), key = |item: &Todo| item.id {
row(class = "todo") { text {{item.label.clone()}} }
}
}
}Why: when the collection changes, the list compares old and new keys and keeps, moves or creates each row. A kept row is not rebuilt; it keeps its nodes, signals, timers and the data it was built with. With real keys, inserting at the front of a thousand rows is one node insertion.
An index is the wrong key. Insert one item at the front of a three-row list:
| Key | Old keys | New keys | Plan | Shown |
|---|---|---|---|---|
item.id | 7, 8, 9 | 6, 7, 8, 9 | create, keep, keep, keep | the new row, then the three old ones |
| the index | 0, 1, 2 | 0, 1, 2, 3 | keep, keep, keep, create | the old rows unchanged, then the last item again |
With index keys the new item never appears.
Two rows with the same key panic, in every build profile.
Virtualise long lists
Build only the rows the scrollport can show. The component library ships a virtualised list:
use zgui_ui::prelude::*;
view! {
VirtualList(
count = lines,
row_size = 22.0,
label = "Log",
row = move |index: usize| view! { text {{move || format!("line {index}")}} }
)
}Why: scrolling, resizing and restyling all cost more as the number of boxes grows. A virtualised list keeps that number at what fits on screen, so its cost does not grow with the row count. Without it, one scroll frame over 20 000 mounted rows takes about 790 ms (numbers).
If you build your own:
- Stand in for hidden rows with padding on the container, written with
style:padding-topandstyle:padding-bottom(why), not with empty elements. - Declare row heights. Measuring row 4 200 means building it.
- Slide the window, so kept rows keep their keys. Scrolling by one row then destroys one row and builds one.
Styling
Toggle a class on the element it styles
.cell.hot { background-color: rgb(47, 107, 255) } /* class on the element: cheap */
.warm .cell { background-color: rgb(47, 107, 255) } /* class on an ancestor: costly */Why: a class change on an ancestor restyles every descendant the rule could match. On the reference workload the ancestor toggle costs about fifteen times as much as the local one. A class that no selector mentions costs nothing: zgui checks the selector set before scheduling style work.
Theme with custom properties on a container
Set theme values as custom properties on a container rather than swapping style sheets.
Why: when a custom property changes, only elements that read it recascade. Elements that do not read it take the new inherited values without matching, and subtrees that read none of it are skipped. Replacing an installed sheet re-matches every element, and in that frame the filters that let a class change skip unaffected elements are off. Adding a new sheet invalidates only what its own selectors match.
Write per-frame values on the element
A value that changes on many frames, such as a drag offset or a scroll-linked position, belongs on the element that uses it:
box(
class = "handle",
style:transform = move || Some(format!("translateX({}px)", offset.get()))
)Why: a custom property inherits, so every descendant takes the new value on every change. A
style: property touches one element. Moving the zgui-ui virtual list's spacers from custom
properties to style:padding-top halved the cost of a recycle frame.
Prefer colour, opacity and transform changes to size changes
| Change | Reaches |
|---|---|
color, background-color, a border colour, a shadow, opacity, transform | restyle, paint, draw |
width, padding, gap, font-size | restyle, layout, paint, draw |
Why: a size change relays out the box, its descendants, and its ancestors up to the first whose
size does not depend on it. The same holds for animation: a transition on opacity or transform
never enters layout, while one on width does on every frame.
Changes that happen together are also cheaper when they are near each other. A frame's damage is at most six rectangles, and beyond that nearby rectangles are merged.
Avoid intrinsic sizing you do not need
fit-content, min-content, max-content and an auto flex basis ask the content how big it wants
to be. A fixed size, a percentage or a flex share asks nothing.
Why: answering means laying out the subtree at its minimum and maximum content size, and for text
that means shaping it. zgui keeps the answers across frames, so a settled document measures nothing,
but every content, style or scale change measures again. Grids multiply the cost, because track
sizing asks each item several sizing questions per pass. Compare SizesMeasured with SizesHeld to
see it.
Avoid effects that need an offscreen target
A stacking context only changes paint order and is cheap. An offscreen target is a texture the subtree is drawn into first, which costs memory and a composite on every frame that reaches it.
| On an ancestor | Offscreen target? |
|---|---|
opacity below 1, over children whose ink does not overlap and with no blending descendant | no: the alpha is folded into each primitive |
opacity below 1 over overlapping ink, or with a blending descendant | yes |
opacity: 0 | no: nothing is drawn |
a 2D transform, translate, rotate or scale | no |
perspective, transform-style: preserve-3d, backface-visibility: hidden | yes |
any filter or backdrop-filter | yes |
a custom shader in --zgui-filter or --zgui-backdrop-filter | yes |
a custom shader in --zgui-shader (it paints the box) | no |
mix-blend-mode other than normal | yes |
isolation: isolate | yes |
a clip-path shape or box keyword | yes |
Why: a fade written as opacity on a panel whose children do not overlap costs no target, while a
filter: blur(…) on an ancestor costs one every frame. GroupTargets counts them.
Text
Avoid replacing large text often
Why: a text hole that produces the same string writes nothing. A new string costs one shaping
pass, proportional to the paragraph's bytes, so one large replacement can dominate a frame even
though only one paragraph changed. TextBytesShaped shows the volume.
Recolour and resize text freely
Why: the colour is not part of what is shaped. Glyphs draw through a paint slot, and a theme change or colour transition rewrites the slot. A width change re-breaks lines without reshaping, and each paragraph remembers its last four line-breaking widths.
Make frequently changing labels repeat
Labels that change every frame, such as axis ticks on a zooming plot, each cost one shaping pass. If the values repeat, format them so the strings repeat too.
Why: shaped paragraphs are cached by content, so a repeated string is a cache hit. When a frame has 16 or more new strings, the shaping is spread across the layout workers; fewer are shaped on the frame thread, where that is cheaper.
Drawing
zgui draws each vector shape by the cheapest route that can draw it: analytic quads for circles, rectangles and simple strokes, shared mark payloads for many recognised primitives, path glyphs for repeated outlines, atlas masks for small solid paths, a CPU-rasterised layer for a still, complex drawing, and a general GPU rasteriser for the rest. These guidelines keep content on the cheap routes. Vector and canvas covers the API and Paint and scene covers the routes.
Reuse sources and geometry
- Use one source for repeated icons. A source text is parsed once, and every element that draws it shares its shapes.
- Recolour through
coloror--zgui-fill. Colour is never part of a geometry key, so a recoloured icon re-rasterises nothing. - Build unchanging canvas paths once and keep them in an
Arc. Push them withShapeBuilder::shared(Arc::clone(&path)). Recognition, payloads and encodings are keyed by the path's allocation, so a draw closure that rebuilds its paths on every run misses every cache.
Plot data as a Series
use std::sync::Arc;
use zgui::canvas::{Brush, Lod, Series};
use zgui::elements::kurbo::{Affine, Stroke};
use zgui::prelude::*;
let data: Arc<[[f32; 2]]> = samples.into();
let plot = CanvasHandle::new();
plot.draw(|scene| {
scene.push_series_lod(
Series::Line {
data: Arc::clone(&data),
to_canvas: Affine::scale_non_uniform(2.0, -40.0),
stroke: Stroke::new(1.5),
brush: Brush::Inherited { alpha: 1.0 },
},
Lod::Columns,
);
});
// On every drag step: move the view, not the data.
plot.set_transform(Affine::translate((dx, 0.0)));Why: a Series (Points or Line) is drawn as one union mark per part, from a payload built
once per data allocation. Thousands of separate shapes, or one path with thousands of subpaths, cost
far more.
- Pan and zoom with
set_transform. It changes no content, so nothing is recognised again and every payload is kept. Rebuilding the scene for a pan throws all of that away. - Keep the data in one
Arc. The payload is found again by the data allocation. Points far from the origin keep their precision. - Turn on line reduction for dense lines.
push_series_lod(series, Lod::Columns), or--zgui-vector-lod: columnson the element, reduces a left-to-right line with many more points than device columns to each column's first, lowest, highest and last points. A pan then builds nothing, and a zoom rebuilds only past twice or half the scale. It is opt-in because, on noisy data denser than a pixel, the reduced line looks lighter under antialiasing. - Use
Marker::Pathfor custom markers. Path markers are drawn as path glyphs, so panning and zooming rasterise nothing. Keep them under 64 device pixels across and do not rotate or skew the element.
Very large series need nothing from you. A series of 65 536 points or more builds its payload on a worker thread and draws a provisional version until it is ready, and a large payload draws only the chunks near the view.
Keep repeated outlines small and simple
A shape whose subpaths repeat a few outlines (a scatter of triangles, crosses or stars) is drawn like text: each distinct outline is rasterised once per device scale, and a pan rasterises nothing. It stays on this route when it has:
- at least 8 subpaths, with few distinct outlines (at most 16 in the first 64, and at most one in eight overall);
- each subpath within 64 device pixels of its first point;
- a solid or inherited paint, no clip and no dash pattern;
- an element transform that keeps the axes (scale, mirror, quarter turn), with equal scales for a stroke;
- no self-intersecting subpaths, and no overlapping subpaths that use the even-odd rule or wind in opposite directions.
Keep complex drawings still
A drawing with gradients or clips that the cheaper routes cannot draw, and no series, is rasterised on the CPU into one atlas tile and drawn as one sprite. Moving it by whole pixels redraws the same sprite, and a static page of such drawings never starts the GPU vector rasteriser.
- Scale it, but do not rotate it. The element's transform must be a positive scale; a turn, skew or mirror uses the general route.
- Let zooms settle. During a zoom the nearest cached scale is stretched, and three frames after the zoom stops the drawing is rasterised at the new scale.
- Do not animate its content. A drawing rasterised three times within 30 frames is kept off this route for the next 30.
Large drawings are handled for you: over 2 048 pixels a side or 4 MiB, a drawing is cut into 512-pixel tiles, and an edit to one canvas shape re-rasterises only the tiles it touches.
Clip a canvas with a box
A canvas does not clip its drawing. Put it in a box with overflow: hidden.
Check which route a shape took
The VectorRoute* counters (VectorRouteAnalytic, VectorRouteMarks, VectorRoutePathGlyphs,
VectorRouteMask, VectorRouteLayer, VectorRouteGeneral) count shapes per route. If
VectorEncodeMisses, VectorLayersRasterised or PathGlyphTilesRasterised rise during a pan,
something is being rebuilt that should be reused. VectorTierChanges counts shapes switching between
the mask route and another.
Resize
Do not debounce resizes yourself
Why: the frame loop already merges size changes that arrive within one frame of the display, and a resize to the current size runs no frame. A resize also does not reshape text, and only what moved is repainted.
Reduce what a size change reaches
A resize lays out every box again. You control how much work that is:
| Do | Why |
|---|---|
| keep fewer boxes in the window | a resize costs about 1 µs per box; virtualising is the largest single saving |
use percentages and flex shares instead of vw and vh | every element that resolved a viewport unit is recascaded on every size change |
| keep media-query breakpoints few | a resize that crosses no breakpoint changes no rule; one that crosses a breakpoint re-matches |
| avoid unneeded intrinsic sizing | each new measurement is a nested layout of the subtree |
| make size observers settle | an observer whose handler keeps changing layout costs extra passes and, past the pass budget, an extra frame (ObservationsTruncated) |
Moving a window to a display with a different scale factor costs more than a resize and cannot be avoided: it discards all layout and misses every cache keyed on device pixels.
Find a slow frame
Start with the cheapest question. Check that a still window draws no frames at all, then read the work counters for one slow interaction, then record a latency trace to see where the time went. Measure your own application shows how to do each.