D.A.B.Tv0.0.33 Tutorial API DABT Tools ↗ GitHub ↗

Developer Guide: Designing Fast Apps

How to write pages and callbacks that stay under the perceived-instant budgets. Every recommendation here comes from a measured change to the demo app; the numbers are in section 9.

1. Budgets

A page switch under 100 ms and input feedback under 50 ms feel instant. These are the lines the profiler (tools/benchmarks/profiler) rates against:

interaction budget
hover, focus, click 30 to 100 ms
page switch 100 to 150 ms
an addon switched on or off, content regenerated (tui.page.refresh) 100 ms, the same as a page switch
palette, dialog open or close 100 ms
resize 250 ms
idle 2 repaints per second at most

The framework already makes the common work cheap (page snapshots, a style cache, row and geometry caches, one synchronized flush per frame). What is left is your code: a callback that forks five times costs more than the whole render of a simple page.

2. The cost model

Rough prices on a desktop machine, in bash 5:

operation cost
builtin command ([[ ]], (( )), printf -v) 1 to 3 µs
associative array lookup ${A[$k]} 2 to 3 µs
function call 2 to 5 µs
$( ) of a function (a fork, no exec) 0.3 to 1 ms
$( ) of an external program (fork and exec) 1 to 3 ms, more under load
pipeline of n programs n forks and n execs
waiting on a child that ignores SIGTERM 50 ms

Two consequences:

  • One fork is worth a few hundred array lookups. Removing forks beats shaving arithmetic.
  • Lookups add up. A widget redraw is about 100 lookups, so about 300 µs. Do not redraw widgets you did not change.

3. Measure first

Never tune by feel.

tools/bench/page_switch.sh 40          # headless: render, layout, flush spans, bytes per switch
tools/benchmarks/profiler/profile.sh --scenario nav --rounds 5     # the real app in a pty: latency per interaction
tools/benchmarks/profiler/profile.sh --deep       # also a per-function trace, forks per call site

In your own app: _tui_perf.begin NAME / _tui_perf.end NAME around a phase, tui.perf.report, or TUI_PERF_LOG=FILE. The profiler report lists forks per call site (attr.forks) and time per function and per page; read those two first. Compare against the run before your change, not against a feeling. There is no public span call yet (_tui_perf.* is the documented exception). For a quick number in app code, take ${EPOCHREALTIME//[!0-9]/} before and after a phase and log the difference with tui.log.info, behind an environment switch.

A trivial page still costs about 120 ms to revisit in the profiler: about 23 ms cache replay, 28 ms render and about 33 ms of probe and settle overhead. Anything above that is page code or layout.

4. Callbacks: no forks on hot paths

“Hot” means: on_visit, tick callbacks (tui.every, _TUI_TICK_FN), input handlers, anything that runs per keystroke or per refresh.

4.1 Read widgets into variables, and use tui.capture instead of $( )

The getters you use most have a variable form that costs nothing:

tui.get inp_name name              # not: name="$(tui.get inp_name)"
tui.list.selected lst_tasks i      # not: i="$(tui.list.selected lst_tasks)"

For any other command whose output you need, tui.capture:

# slow: a subshell per call
id="$(tui.get.focused)"
pos="$(tui.text.cursor wx_text)"

# fast: runs in the current shell, no fork
tui.capture id tui.get.focused
tui.capture pos tui.text.cursor wx_text

tui.capture VAR CMD ARGS... stores the stdout of CMD in VAR with trailing newlines stripped, exactly as $( ) does. The status of CMD is returned. A widget status line that ran five captures every 0.3 s forked 17 times per second just to stay idle; with tui.capture it forks never.

Because CMD runs in the current shell, variables it sets stay set. That is almost always fine, but do not rely on $( ) isolating a callee’s globals.

4.2 Replace external programs with builtins

instead of use
$(date +%H:%M:%S) printf -v now '%(%H:%M:%S)T' -1
$(date +%s) printf -v now '%(%s)T' -1
$(cat file) $(<file) (bash reads it, no fork)
$(basename "$p"), $(dirname "$p") ${p##*/}, ${p%/*}
$(echo "$x" \| sed 's/a/b/g') ${x//a/b}
$(printf '%s\n' "${arr[@]}") printf -v out '%s\n' "${arr[@]}" (then strip the trailing newline, see 4.4)
$([[ cond ]] && echo on \|\| echo off) if [[ cond ]]; then v=on; else v=off; fi
$(IFS=,; echo "${a[*]}") local IFS=,; v="${a[*]}" inside a function
df \| tail -n +2 \| awk '{...}' one df, parsed with read -r a b c d e f
$(nproc) on every visit compute once, see 5.2
awk for integer arithmetic (( )); use awk only for floating point

Pages that read /proc do it with while read -r ... loops, never cat, grep or awk.

4.3 What a fork-free callback looks like

_mon_refresh_disk() {
    local now_ts device pct target _hdr
    printf -v now_ts '%(%s)T' -1                    # was: now_ts="$(date +%s)"
    {
        read -r _hdr                                # one df instead of df | tail | awk
        while read -r device _ _ _ pct target _; do
            entries+=("${target##*/}:${pct%\%}")
        done
    } < <(df -P -x tmpfs -x devtmpfs 2>/dev/null)
    tui.capture bars hbar_string -w "$w" "${entries[@]}"   # was: bars="$(hbar_string ...)"
}

4.4 Behaviour to preserve

$( ) strips all trailing newlines. printf -v does not. When you convert, strip them yourself so the text stays identical:

printf -v out '%s\n' "${lines[@]}"
out="${out%"${out##*[!$'\n']}"}"      # trailing newlines off, as $( ) did

tui.capture already does this. Compare old and new output byte for byte after a conversion; the demo conversions were all checked that way.

5. Do not repeat work that cannot have changed

5.1 Memoise static output, keyed on its inputs

Renderer output (banner, table, hbar, …) depends only on its arguments and the renderer width. Build it once per width:

declare -gA _SC_ALL_MEMO            # NO "=()": see below

show_all() {
    local key="${TR_WIDTH:--}|$_SC_W"
    if [[ -z "${_SC_ALL_MEMO[$key]+x}" ]]; then
        # ... build "$out" with tui.capture ...
        _SC_ALL_MEMO[$key]="$out"
    fi
    tui.output output "${_SC_ALL_MEMO[$key]}"
}

The key must contain everything that changes the output (here the width). A result that depends on data (a live value, a file that may change) is not memoisable; leave it uncached.

5.2 Scripts are re-sourced on every visit

A page’s <script> runs again each time the page is entered. Two consequences:

  • declare -gA memo=() resets the memo on every visit. Write declare -gA memo without a value: it creates the array once and keeps it.
  • Anything expensive at the top level of the script runs per visit. _MON_NPROC="$(nproc)" forked on every visit; guard it:
declare -g _MON_NPROC
[[ -n "$_MON_NPROC" ]] || _MON_NPROC="$(nproc 2>/dev/null || echo 1)"

5.3 Cache on content, not on counters

When you cache a result, key it on the inputs that produce it. Do not rely on “I bumped a version counter whenever X changed”: one mutation path that forgets to bump leaves a stale screen that is hard to find. The framework follows this rule (row, geometry and line-slice caches are keyed on their inputs), and a stale entry is then impossible by construction. A wrong key can only cost a miss, never a wrong result.

5.4 Compute interval text once

Text derived from a setting that changes rarely (a refresh interval, a label) does not need an awk on every refresh. Memoise it on the setting (_MON_INTERVAL_S[$ticks|$poll]).

6. Layout and widgets

  • Panes cost. Each pane is drawn, laid out and key-hashed on every full render. Prefer fewer, larger panes; nest only where the structure is real. Do not add wrapper panes for spacing; use hpad/vpad.
  • Consistent geometry is cheaper. The shared menu is 18% wide on every page, so its rectangles and the cached geometry for its 15 buttons are identical across pages and are reused.
  • Pick plain widgets for static content. Labels, buttons and checkboxes with plain text are cached by the framework. A text containing ${expr} is re-evaluated (and forks) on every draw and bypasses the cache; keep dynamic text in a variable you update with tui.update, not in an expression.
  • Do not restyle every frame. A pane or widget fragment is cached under its geometry, text, state and the style strings it draws with, so a restyled widget only misses for itself, and an identical widget on another page (the menu, the header) hits. Restyling in a tick callback still recomposes what it touches on every frame, and the frame must be flushed. Style once, then change text.
  • Update, do not rebuild. tui.update ID TEXT changes one widget. Rebuilding a tab strip or grid (tui.tabs.build, tui.grid) on every visit costs tens of milliseconds; build once and keep it when the content is unchanged.
  • Output panes. Lines with colour are measured and sliced in bash and memoised per line, so scrolling back is cheap. Very large outputs (thousands of lines) still cost to split into lines; page or truncate long documents when the user does not need all of it at once.

  • Change pages in place. When an addon is switched or generated content changes, call tui.page.refresh instead of tui.goto the same page: it rebuilds only the changed panes, in a fraction of the time (section 12).

7. Timers, ticks and background work

  • Prefer tui.every SEC FN ID over _TUI_TICK_FN or a tick counter. A tick callback runs on every iteration of the main loop (20 times a second at the default poll), so “do the work every N ticks” pays a call per iteration just to count, ties the interval to the poll rate, and its widget updates are not batched. A tui.every job fires on wall-clock time, runs inside the batch that draws each touched widget once, and is removed when the page is left (pattern 14.1). Make the work fork-free (section 4).
  • tui.every SEC FN ID and tui.after are cheaper than a polling loop in a tick callback. Always cancel with tui.every.cancel when the page is left; a leaked timer is permanent idle cost.
  • Slow work goes to tui.job.run. It runs in a separate process, so it may fork as much as it likes; the main loop stays free for keys and the mouse, shows a spinner when the work passes 100 ms (--delay changes that) and calls your done function, the one place the result is drawn, when it is finished. Nothing appears half-finished. tui.page.rebuild is the same idea for a whole page.
  • Nothing should repaint while the app is idle. A clock that updates once per second is fine; a blinking cursor or an animation timer is not. Idle must stay under 2 repaints per second.
  • Processes started with tui.exec are killed when the page is left. An interactive shell ignores SIGTERM; the framework now follows up with SIGHUP, which turns a 55 ms wait into 11 ms. If you launch your own long-lived child, make it exit on SIGHUP or SIGTERM promptly.

8. What the framework does for you, and what defeats it

mechanism what it saves what defeats it
page snapshot cache parse and build on revisit, and the per-switch stat an edited page or dependency is detected at start-up only; while the app runs the cache is trusted (TUI_CACHE_TRUST=0 re-enables the live check); <script> and on_visit always run fresh
row cache (_tui_rowcache) recomposing unchanged panes and plain widgets, about -45% render on a content-heavy page ${expr} texts, a changed style, geometry or text (only for the fragment concerned)
widget geometry memo recomputing positions a changed placement or size attribute, a resized pane
line-slice and width memos re-measuring and re-slicing coloured output lines new line text (it is a miss, not an error)
tui.modal.dismiss re-rendering the page under a closing overlay (palette close 38 ms to 14 ms) anything painting, restyling or resizing while the overlay is open (it falls back to the full repaint)
page refresh (tui.page.refresh) a full rebuild (parse, build, layout) when an addon or generated content changes: only the changed panes are rebuilt, from a tree the page remembers a change outside the panes, a pane without an id, <tabs> or a widget that points at its pane with pane="..." in the changed part: it falls back to a background rebuild with a spinner
one paint per page switch tui.goto renders the whole screen once; a draw made while the page loads (tui.update, tui.focus, a pane border in on_visit) returns before it composes anything, and output queued before that frame is not painted a second time. A docu switch went from 5 writes and 41 KB plus a 9 KB repaint to one 32 KB write a draw after tui.goto returns (a timer, a hook on page) is a normal draw; before tui.run nothing is dropped
one paint per button click the release of a button whose action rendered the whole screen (a page switch) does not draw the button, its pane’s border or the old hover target again an action that renders nothing still gets the un-press draw; a draw in your own callback after tui.goto returns is a normal draw
TUI_ROWCACHE=0, TUI_DISMISS_REPLAY=0 switch the caches off to check whether one causes a problem  

Use tui.modal.dismiss for esc and click-outside. Use tui.modal.close when a command runs after the close, because the saved page cannot know what the command changes.

9. What the demo gained

Two deep profiler runs, 5 rounds, settle medians (same machine and size): 195825 before and 201315 after the demo page changes (fork-free callbacks, memoised static output, one navbar width).

  before after
page switch by key (alt+2, components) 201 ms 106 ms
page switch, first visit 204 ms 184 ms
page switch, revisit 168 ms 156 ms
settings, first visit 278 ms 176 ms
components, revisit 215 ms 157 ms
monitor, revisit 228 ms 186 ms
theme switch, first use 242 ms 215 ms

Interactions the changes did not touch (hover, focus, click, scroll, palette, resize, startup) did not move (within 3%).

In the demo, each of these paid off most:

  1. The show_all renderer view built 13 renderers through $( ) on every visit. Fork-free and memoised per width it went from the largest item on the page to one lookup.
  2. The monitor refresh forked about 20 times per refresh, once a second (date, awk, a capture per chart and per colour list, df | tail | awk, one per pane in the output trimmer). It forks once now (df); nproc runs once per process.
  3. wx_status_tick and _lab_state run several times per second on their pages and forked 5 and 3 times per run. They fork none.
  4. Leaving the Terminal page waited 50 ms for a shell that ignores SIGTERM.

10. Checklist

Before you ship a page, run the profiler on it and check:

  • No $( ), date, cat, awk, sed, basename or nproc in on_visit, tick callbacks or input handlers. Use tui.get ID VAR, tui.capture and builtins.
  • Anything that can take longer than ~50 ms runs through tui.job.run; changes to the page on screen go through tui.page.refresh.
  • Panes that addons or a refresh may change have an id, and their widgets are written inside them.
  • Static output is memoised on every input that affects it; declare -gA memo without =().
  • Nothing expensive at the top level of a <script> (it runs on every visit).
  • No ${expr} text in widgets that redraw often; no tui.style in tick callbacks.
  • Timers started on visit are cancelled on leave; the page repaints nothing while idle (a periodic refresh is a tui.every job, not a tick counter; recomputed values go through tui.update_changed or tui.set_text).
  • Pane count and nesting are no more than the layout needs; the menu width matches the other pages.
  • Old and new output compared byte for byte after any refactor of rendering code.
  • Before and after profiler numbers recorded for anything you call an optimisation.

See also: Callbacks and interactive viewports, Grids and tabs, the measurements in performance-progress and the design background in cheap-redraws-concept.

11. Lessons from the page-switch floor

Measured on the trivial pages (home, layout, case study), where no page code runs: a switch fell from 136 ms to 86 ms by removing framework work, not page work. What carried over to app code:

  • Key a cache on what the result depends on, then count the hits. A fragment cache keyed on a counter that every page switch bumped never hit across pages (57 stores per switch) while a repeat-render benchmark looked fine. A key made of the real inputs (geometry, text, the style strings) lets identical elements on different pages share one entry.
  • Do the rewrite once, where the data is produced. The page snapshot was reformatted line by line on every replay; moving that step to record time cut the restore from 9.5 to 2.6 ms. Look for transformations of data that never changes.
  • Do not repeat work whose inputs did not change. The footer row, its key-hint map, the terminal size and the layout of a replayed page are all functions of inputs that rarely change; each is now skipped (or rebuilt) when its inputs differ, compared by content.
  • Price a suspect untraced before you fix it. xtrace inflates in-shell time unevenly: it blamed 6 ms on re-sourcing page scripts that costs 0.5 ms. Use the trace to find candidates, a timed loop to price them, and tools/benchmarks/profiler/profile.sh --scenario floor to see the breakdown of one switch.

12. What an addon or a refresh costs

tui.page.refresh has the same 100 ms as a page switch, and most of that is the redraw. The work before the redraw (loading the page’s remembered tree, applying the addons, expanding templates, comparing, rebuilding the changed panes) measured on the Addons tab of the Compose demo page at 150 x 45, bash 5.3:

  time before the redraw
nothing changed since the last refresh 27 ms
one addon switched on 43 ms
five addons switched on at once 70 to 105 ms
all five off again 42 ms
Compose page (Board tab), 3 cards x 2 items 59 ms
Compose page (Board tab), 8 cards x 6 items 209 ms
Compose page (Board tab), 20 cards x 9 items 556 ms

The floor is about 27 ms. Above it, a rebuild costs roughly 1.5 to 3 ms per widget it creates, so the time follows what changed, not how big the page is. Three habits keep it low:

  • Keep what changes small. An addon that adds one widget to a pane rebuilds that pane; an addon on the root pane rebuilds the page.
  • Do not generate hundreds of widgets. Past 30 to 40 new widgets a refresh no longer fits the budget. For long lists use one list or table widget; for big generated pages expect the time in the table above.
  • Change only what you must. An addon that sets an attribute to the value it already has changes nothing and costs the floor only.

The redraw is a full frame today (about 15 ms at this size). The framework times the refresh with the page_refresh span; tui.perf.report shows it, and the profiler scenarios addons and generated were written to rate it against the 100 ms budget.

13. Held keys

A held key repeats about every 33 ms, so each press has a third of the 100 ms budget at most. Rules from making focus moves cheap:

  • A focus move knows its dirty set. The old and new widget (and the pane borders only when the keyboard pane changes) are drawn as one raw frame, without the row diff.
  • Search structures read the hit index, not per-widget geometry. Arrow-key focus search reads the rects the hit index already holds (_TUI_HZ_WR/WC/WW) instead of one _tui._widget_pos per focusable per press: 80 -> 8 ms per hold action on the Scrolling page.
  • Measure held keys at the real repeat rate: tools/benchmarks/profiler/profile.sh --scenario held. Lag is key sent to first output; judge the worst press.
  • tui.set stores a value, tui.update stores it and redraws. A visit callback that calls tui.set on a visible checkbox or input shows the old state until the next hover; use tui.update.

14. Copy-paste patterns

Each pattern is the shape the demo callbacks use. They are small enough to paste and adapt; where one would be long to write by hand, the framework has a function for it.

14.1 Refresh something every second

refresh_stats() {                       # called as: refresh_stats JOB_ID
    tui.sys.cpu
    tui.update_changed lbl_cpu "CPU ${TUI_SYS_CPU}%"
}
on_stats_visit() { tui.every 1 refresh_stats stats_job; }
  • Not _TUI_TICK_FN with a counter (((++n % 20 == 0)) && refresh): that calls your function 20 times a second to count, and its updates are not batched.
  • The job runs on wall-clock time, so a slow poll rate does not stretch it. Updates inside it are drawn once, together, after it returns.
  • It is removed when the page is left. Calling tui.every again with the same ID changes the interval (the monitor page does this when you type a new interval); there is never a second job.
  • To stop it earlier, tui.every.cancel stats_job.

14.2 Update only what changed

tick() {
    tui.update_changed lbl_status "$text"   # widget: nothing is drawn when the value is the same
    tui.set_text log_pane "$log"            # pane: same rule, built in
}

tui.update always draws. A poll that recomputes the same text three times a second repaints three times a second for nothing. tui.update_changed costs one string comparison when nothing changed. Panes already skip unchanged text in tui.set_text. Use tui.update when the screen may be stale (the value was set with tui.set, which stores without drawing).

14.3 Read values without a subshell

tui.get inp_name name                     # not: name="$(tui.get inp_name)"
tui.config.get confirm.quit 0 current     # not: current="$(tui.config.get confirm.quit 0)"
tui.capture state tui.plugin.get "$n" state   # any other command that prints one value

Every $( ) in a click handler costs about 1.3 ms. Three of them in one handler (a plugin menu did this) is a visible hitch on a held key.

14.4 Turn a condition into a word

state=off
[[ ${ST[clock]} == 1 ]] && state=on
tui.notify "clock $state" info 2
# not: "clock $([[ ${ST[clock]} == 1 ]] && echo on || echo off)"

14.5 Keep counters and progress in variables

declare -gi _JOB_PCT=0
job_step() {
    ((_JOB_PCT += 4))
    tui.progress.set prog "$_JOB_PCT"       # not: read the widget back, add 4, write it
    ((_JOB_PCT >= 100)) && tui.every.cancel job_timer
}

The widget is for the screen; the variable is the state. Reading the widget back costs a capture per step and ties your logic to what is drawn.

14.6 Several lines of text without printf '%s\n' |

printf -v text '%s\n' "${lines[@]}"
tui.output pane "${text%$'\n'}"            # one trailing newline off, as $( ) did

14.7 An idle page repaints nothing

An animation (the Home page types its title and blinks a cursor) is a deliberate exception and should end when it is done. Everything else should show 0 repaints a second when no key is pressed: poll with tui.every, compare before drawing (14.2), and let a tui.every job end by tui.every.cancel when its work is finished.

15. A long transcript or log

tui.md.show renders all of the text every time it is called, so a view that is redrawn often gets slower as it grows. Measured in the Chatty app (a streamed answer redrawing the transcript, development machine):

Messages Text One redraw
1 54 B 5 ms
104 15 KB 41 ms
406 55 KB 106 ms
1008 125 KB about 400 ms

At 20 redraws a second that is the whole loop: typing and keys lag. Three changes, in order of effect:

  1. Draw only the newest part. Keep the last N messages (40 in Chatty) and say how many are hidden. A redraw then cost about 27 ms at 406 messages and 26 ms at 1008: flat.
  2. Redraw less often. A typed-out answer at 10 redraws a second looks the same as at 20 with twice the characters per tick. Live streaming polls its stream file at 10 Hz and redraws only when the text changed.
  3. Skip identical frames. Compare with what is on screen and return early.

The cost also depends on the content: tables and code blocks cost more per byte than paragraphs, which is why 6 KB of mixed answers still took about 30 ms.

Other numbers from the same app, for planning: a tab switch in a four-pane deck 35 to 53 ms; a form built with tui.factory plus a relayout about 50 ms (build it once, refresh the values); a six-row linechart 5.9 ms; an empty $( ) 1.3 ms. More in Live output, Charts and Tabs and menus.