Performance
A desktop app is judged by how it feels under the hand: a key that lags or a window that hangs while it reads a
file is a defect, not a slow feature. These rules come from Editora’s
docs/performance.md, the contract
every change on a hot path there must honor.
Rules on this page 23
| ID | Level | Rule |
|---|---|---|
| The UI thread | ||
| PERF-01 | MUST | Never block the JavaFX application thread. No file or network I/O, no process start or wait,
no parsing, searching, hashing or JSON of any size on it, and no Thread.sleep, Future.get(), join() or
Process.waitFor() there. Two exceptions. At start-up, before the first window is shown, start() may wait once
for the config read that PERF-16 began before the toolkit, and may read the bundled resources that
window is built from: its fonts, registered there or by a thread start() waits for once
(ICON-02 requires them before any CSS is applied), the message catalog, the
keymap and its icons. Nothing else at start-up is excepted: a log file opened, a file or a store of the user’s
read (presets, profiles, schedules, themes the user added), a ledger read, a socket bound or a lock taken blocks
the thread as it would anywhere, and so does a font registered on it after the first frame. And as the app quits,
when no frame is left to block, the quit method (WIN-13) or Application.stop() may
make the last save on it: write the settings, the window state and the session, or wait for a write already
under way. An app whose start() loads its settings itself, whether or not main read the file earlier, or
waits for a read begun after the toolkit, has PERF-16’s gap and none here.
|
| PERF-02 | MUST | Touch the scene graph only on the FX thread. Background work hands its result back with
Platform.runLater; nothing else creates, changes or reads live nodes.
|
| PERF-03 | MUST | A background result is applied under a generation guard, so an answer to an old request never
overwrites a newer one.
|
| PERF-04 | SHOULD | Every thread is named and is a daemon.
|
| PERF-05 | MUST | Blocking work stays off the common ForkJoinPool: no supplyAsync or runAsync without an
executor runs a blocking call, and a Process subclass overrides onExit(), whose inherited version is a
waitFor() on that pool.
|
| Hot paths | ||
| PERF-06 | MUST | Redraws are coalesced to at most one per pulse, with a flag that one request is already
queued. A redraw is the painting of what the app draws itself, a canvas, a chart or a grid of cells; in an app
that paints nothing itself, it is the refresh of its list or view.
|
| PERF-23 | MUST | Work driven by text the user types waits for typing to pause (a debounce) when it leaves the
FX thread or cannot finish within a frame: a search of files, a request to a server, a re-highlight. Filtering a
list already in memory, as a command palette does, is exempt and runs on every keystroke.
|
| PERF-07 | MUST | An app that shows a stream as it arrives (the output of a process, log records, progress or
readings from another thread) hands it to the FX thread in batches at least 16 ms apart, never one runLater per
line or record.
|
| PERF-08 | MUST | Work only on what is visible and only on what changed: no O(document) or O(list) work per
keystroke, scroll or tick, and a list the user or the data can grow without a limit the app sets is shown in a
virtualized control ( ListView, TableView, a fixed cell size), which builds nodes for the visible rows only.
Filtering a list already in memory, as a command palette does, is exempt and runs on every keystroke.
|
| PERF-09 | SHOULD | A hot path allocates little: it reuses buffers and arrays, and caches data a repaint only
reads.
|
| PERF-10 | SHOULD | CSS stays cheap: no applyCss() on a large subtree, stable style classes, and spans of the
same style merged before they are applied.
|
| Memory and size | ||
| PERF-11 | MUST | Everything that grows is bounded: logs, histories, consoles, caches, undo. The newest is kept.
|
| PERF-12 | MUST | In an app that opens files or data the user picks, a large input is guarded before it loads:
its size is checked before its content is read, or the read is capped, and what will not fit is never read in.
The app refuses it with a message or opens only the part that fits. Where an input can open with less, without
features the app runs over its content, as a file in an editor can open without highlighting or a minimap, the
app steps down as the input grows: those features turn off past one threshold, and past another it opens
read-only or capped. An input the app can only read in or refuse (an imported theme, a .torrent file) has
nothing to step down to.
|
| PERF-13 | MUST | A closed window releases what it held: listeners, timers, executors, file watchers, native
resources.
|
| Start-up | ||
| PERF-14 | MUST | The first frame comes first: only what the first window shows is built before it. Everything
else builds on first open: a closed panel’s content, the Settings pages, the dialogs and the other windows.
|
| PERF-15 | MUST | What nobody waits for starts after the first frame has painted: the update check, extra
fonts, indexes and caches.
|
| PERF-16 | SHOULD | The config read starts on a thread of its own before the toolkit does, so the two overlap
and the wait for it that PERF-01 allows at start-up, start() taking the result, is short. An app
whose start() loads its settings itself does not meet this, whether or not main read the file earlier.
|
| PERF-17 | SHOULD | The app ships precompiled stylesheets ( .bss). The AOT cache, the other half of a fast
start, is REL-10.
|
| Measure, don’t guess | ||
| PERF-18 | SHOULD | Every change on a hot path says what it costs in its pull request: added FX-thread work,
allocation per keystroke or scroll, extra layout passes, memory. “Negligible” is an answer; no answer is not.
|
| PERF-19 | SHOULD | Start-up is measured by a script that takes the median of several cold launches, and by
phase marks in the app.
|
| PERF-20 | SHOULD | The app can sample its FX thread when something stalls.
|
| PERF-21 | SHOULD | Each hot path that once regressed keeps a headless test.
|
| PERF-22 | SHOULD | A suspected regression gets a number before and after, from temporary System.nanoTime
instrumentation if nothing better exists.
|
The UI thread
Section titled “The UI thread”- PERF-01 MUST Never block the JavaFX application thread. No file or network I/O, no process start or wait,
no parsing, searching, hashing or JSON of any size on it, and no
Thread.sleep,Future.get(),join()orProcess.waitFor()there. Two exceptions. At start-up, before the first window is shown,start()may wait once for the config read that PERF-16 began before the toolkit, and may read the bundled resources that window is built from: its fonts, registered there or by a threadstart()waits for once (ICON-02 requires them before any CSS is applied), the message catalog, the keymap and its icons. Nothing else at start-up is excepted: a log file opened, a file or a store of the user’s read (presets, profiles, schedules, themes the user added), a ledger read, a socket bound or a lock taken blocks the thread as it would anywhere, and so does a font registered on it after the first frame. And as the app quits, when no frame is left to block, the quit method (WIN-13) orApplication.stop()may make the last save on it: write the settings, the window state and the session, or wait for a write already under way. An app whosestart()loads its settings itself, whether or notmainread the file earlier, or waits for a read begun after the toolkit, has PERF-16’s gap and none here.- Check (code):
grep -rnE 'Files\.[a-z]|File(Input|Output)Stream|File(Reader|Writer)|RandomAccessFile|getResourceAsStream|loadFont|HttpClient|openConnection|openStream|new Socket|SocketChannel\.open|ProcessBuilder|getRuntime\(\)\.exec|\.waitFor\(|Thread\.sleep|\.join\(\)|uture[A-Za-z]*\.get\(|\.get\([^)]*TimeUnit|invokeAndWait|\.await\(' src/main/javalists the candidates: the lines that read or write a file or a bundled resource, open a connection, start or wait for a process, sleep, or wait for another thread. Each line is judged by reading what calls it. It is fine when only an executor’s task or a thread’s body reaches it; whenstart()reaches it before the first window is shown and it is one of the things the statement allows there, the onejoin()orget()on the config read begun before the toolkit, or the reading of a resource bundled with the app that the first window is built from: the registering of the fonts it draws with (Editora’sFonts.loadForFirstPaint) or the one wait for the thread that registers them, the message catalog (Editora’sMessages.init), the keymap (Editora’sKeymapManager.loadNamed) or the window’s icons; or when it is the last save, made by the quit method orApplication.stop(), which may do nothing else that blocks. It is a violation when an event handler, a listener, aPlatform.runLaterbody, a timer’s or an animation’s callback, orstart()reaches it on the FX thread, itself or through a method it calls: a handler that calls a settings store’ssave()writes the file on the FX thread. Instart()everything else is a violation, before the first window is shown or after: a second wait for the config, a log file opened, a file or a store of the user’s read (presets, profiles, schedules, a folder of themes the user added), a ledger read, a socket bound, a lock taken. Only the settings are left to PERF-16: a load of them made instart()itself, whether or notmainread the file earlier, and a wait for a read of them begun after the toolkit. A font registered on the FX thread after the first frame is a violation too. A grep finds only the spellings it is given: read the handlers and listeners too for parsing, searching, hashing or JSON done in place, and for a wait under another name. - Reference: Editora
docs/performance.md§1; its one start-up wait istakeBootstrapinApp.java, which joins theconfig-prefetchread, andFonts.loadForFirstPaint, called next, registers its first fonts (ui/Fonts.java); theconfig-prefetchthread reads the catalog too, andstart()reads it only when that thread picked another language (Messages.init). Mirada’sstart()makes the two waits the first exception allows:settings()joins the settings read, which also reads its catalog (in its jlink image that read begins after the toolkit, which is PERF-16’s gap and none here), andFonts.ready, before the window is shown, joins the thread that registers its fonts (App.java,ui/Fonts.java). For the last save, the app template’sMainWindow.quitwaits for the settings write on a background thread and exits from there, which needs no exception, and itsApplication.stop()then waits for the writer once more on the FX thread (Running.closeinui/Startup.java), which the second exception allows; Termina’sWindowManager.closeAll, run fromApplication.stop(), flushes its settings on the FX thread, which the second exception allows. The app template does its start’s file work off the FX thread:prepareinui/Startup.java, which refuses the FX thread and runs on a thread of its own while the toolkit starts, opens the Debug Log’s session file, reads the settings, the catalog andpauta.jsonand binds the single-instance socket;start()then registers its first fonts, which the first exception allows (Fonts.load), and the remaining font is registered off the FX thread after the first frame (Fonts.loadDeferred). No app has been read through for the rule yet, and none holds it everywhere. Found so far: Editora’sstart(), in thatApp.java, does on the FX thread, before its first window is shown, what no exception covers: its calls toDebugLog.attachFile(the Debug Log’s session file),SharedConfig.claimInstance(the lock on a file in the config folder),ProcessRegistry.reapOrphans(the ledger of the servers it started),McpServer.reapStaleEndpoint(a stalemcp-endpoint.json) andThemes.loadUserThemes(the user themes’ folders). Some of its handlers still touch the disk too, for examplerenameFileTo(Files.exists,Files.move) andopenPersonalDictionary(Files.writeString) inui/MainController.javaand the new-folder prompt inui/ProjectPanel.java(Files.createDirectories). Torrenta’sstart()reads its catalog, which the exception allows, and opens that file the same way (DebugLog.attachFilein itsApp.java); its main window’s constructor, before the window is shown, reads six stores of the user’s (the profiles, the labels, the watch folders, the search providers, their definitions and the RSS feeds, inui/MainWindow.java), andstart()readsprofiles.jsonagain once the window is shown (Startup.profile). Termina reads its settings, its first fonts, its catalog and its imported themes inApplication.init(), off the FX thread (preparein itsApp.java); building its first window then reads the bundled keymap (ui/Keymap.java, on the firstKeymap.defaultFor) and decodes the window’s icons (ui/Icons.java,Icons.applyTo) on the FX thread, which the exception allows, and once the window is shownstart()deletes a stale socket file and binds the socket for later launches there, which it does not (serveininstance/SingleInstance.java). It also registers its remaining font families on the FX thread after the first frame, which no exception covers (Fonts.loadRest, called from thatApp.java). Mirada, on macOS, compares two paths on the FX thread when it was started with a file and the OS hands it its first one (Files.isSameFileinos/MacOpenFiles.java). nux waits up to two seconds for the tray icon’s removal in the handler of Settings’ Save (AwtTray.dispose, reached fromTrayController.settingsSaved) and writes its--screenshotfile from an animation’s callback (ui/Screenshot.java). Torrenta writes its settings from the listeners of its Settings rows (saveQuietlyinui/SettingsWindow.java) and asks the file store for the free space on each keystroke in a save-folder field (updateFreeSpaceinui/LocationDialog.java). Modula reads its presets and its schedules in its pane’s constructor, before the window is shown (config.loadPresetsandconfig.loadSchedulesinui/RadioPane.java), writes its presets and settings from handlers (config.savePresetsandconfig.saveSettingsin that file) and, building its Settings window, startsffmpeg -versionand waits up to five seconds for it (Encoders.isAvailable).
- Check (code):
- PERF-02 MUST Touch the scene graph only on the FX thread. Background work hands its result back with
Platform.runLater; nothing else creates, changes or reads live nodes.- Check (code):
grep -rnE 'new Thread\(|Thread\.(ofVirtual|ofPlatform|startVirtualThread)|\.(submit|execute|schedule|scheduleAtFixedRate|scheduleWithFixedDelay)\(|(supply|run)Async\(|\.(thenAccept|thenRun|thenApply|thenCompose|whenComplete|handle|exceptionally)(Async)?\(' src/main/javalists the candidates: the lines that start a thread, hand a task to an executor, or add a step to a future that completes off the FX thread. Each line is judged by reading the task’s body. It is fine when the body touches nothing a scene shows, or touches it only insidePlatform.runLater. It is a violation when the body, or a method it calls, sets a control’s value, changes an observable list a view shows, or reads a live node’s state outside arunLater. A callback that a library runs on a thread of its own (a file watcher, a process’s reader, a logging handler) is a task body too, and the grep does not list those: read the listeners the app gives its services as well. - Reference: Editora
git/GitService.java: every task it gives its workers hands the result to its caller insidePlatform.runLater. No app has been read through for the rule yet.
- Check (code):
- PERF-03 MUST A background result is applied under a generation guard, so an answer to an old request never
overwrites a newer one.
- Check (code):
grep -rn 'runLater' src/main/javalists the candidates: the lines where another thread hands something to the FX thread. Each line is judged by reading it. It needs the guard when what it applies answers a request that can be made again before the answer comes: a search, a load, a status or completion query that typing, a selection or a refresh starts. There each request takes a mark that the next request replaces (a counter, as Editora’sAtomicLong.incrementAndGet, or a helper that keeps the latest request only, as Editora’sLatestOnly), and the answer is applied only while its mark is still the newest, compared inside therunLater. It is a violation when such an answer is applied with no comparison, or with one made only before therunLater. A line needs no guard when nothing newer can replace what it hands over: an event, a batch of a stream, a result asked for once at start-up. - Reference: Editora
git/GitService.java(refresh, with itsrefreshGencounter),search/SearchService.javaandui/LatestOnly.java(LatestOnlyTest); Termina (work/LatestOnly.java) and Mirada (ui/LatestOnly.java) carry the same helper. No app has been read through for the rule yet. Found so far: nux applies each Refresh of its Events window, and each load of the Energy and Outages tabs of its History window, with no mark (ui/EventsWindow.java,offFxinui/HistoryWindow.java), beside a Charts tab that numbers its loads and applies only the newest.
- Check (code):
- PERF-04 SHOULD Every thread is named and is a daemon.
- Why: a thread dump then says what is running, and a stray worker never keeps the app alive after its last window closes.
- Check (code): every
Executors.new…andnew Threadgets a name andsetDaemon(true), through a thread factory such asdaemon("my-feature"); virtual threads are daemons already. - Reference: Editora
terminal/TerminalExecutors.java(itsdaemon(name)thread factory); the canonical shape is in The UI thread.
- PERF-05 MUST Blocking work stays off the common
ForkJoinPool: nosupplyAsyncorrunAsyncwithout an executor runs a blocking call, and aProcesssubclass overridesonExit(), whose inherited version is awaitFor()on that pool.- Why: the common pool has one worker fewer than the machine has cores, so a few blocked waits
(
CompletableFuture.supplyAsyncof awaitFor) starve every other user of it. - Check (code): no
supplyAsyncorrunAsyncwithout an executor wraps a blocking call (a wait, a read or write of a file, a socket or a process), and every class that extendsProcessoverridesonExit(). An app with noProcesssubclass has only the first half to show. - Reference: Editora
process/ExitWatch.java,docs/gotchas.md. Editora’sDapManager.reportJavaExitstill waits up to 3 s for an exit code in asupplyAsyncon the common pool, and Termina’shandOffininstance/SingleInstance.javaconnects to a socket, writes and reads in one.
- Why: the common pool has one worker fewer than the machine has cores, so a few blocked waits
(
The canonical shape, where daemon(name) is a small factory that names the thread and marks it a daemon, as in
Editora’s TerminalExecutors:
private final ExecutorService exec = Executors.newSingleThreadExecutor(daemon("my-feature"));private final AtomicLong gen = new AtomicLong();
void request(String input, Consumer<Result> onResult) { long mine = gen.incrementAndGet(); exec.submit(() -> { Result r = computeOffThread(input); // heavy work, off the FX thread if (mine == gen.get()) { // superseded? drop it Platform.runLater(() -> { if (mine == gen.get()) onResult.accept(r); }); } });}For one-off blocking calls (reading a file, stat-ing a path, starting a process), a named virtual thread
(Thread.ofVirtual().name("my-read").start(…), the name being PERF-04’s) is enough; the result still
comes back through Platform.runLater.
Hot paths
Section titled “Hot paths”A hot path is what runs on every keystroke, scroll pulse or progress tick. In Editora they are typing, scrolling, highlighting, the overlays and the gutter. In Torrenta they are the transfer table’s refresh, in Termina the terminal grid, in Mirada stepping between images.
- PERF-06 MUST Redraws are coalesced to at most one per pulse, with a flag that one request is already
queued. A redraw is the painting of what the app draws itself, a canvas, a chart or a grid of cells; in an app
that paints nothing itself, it is the refresh of its list or view.
- Check (code): a redraw request sets a flag (Editora’s are named
…Pending) and schedules one pass, and a request that finds the flag set schedules nothing. A handler that paints, or in an app that paints nothing refreshes its list or view, straight from its event has no such flag and fails: a chart drawn from its width listener and again from its height listener draws twice for one resize. Setting a control’s own property in a handler (a label’s text, a progress bar’s value) is not a redraw: JavaFX draws the control once on the next pulse. - Reference: Editora
docs/performance.md§2 (theredrawPendingshape) andui/WindowToolbar.java(scheduleEditStateRefresh, with itseditStateRefreshPendingflag).ui/FxThrottle.javais another tool: a leading-edge throttle with a maximum wait and no such flag, which runs the first request of a burst at once and then at most one per interval.
- Check (code): a redraw request sets a flag (Editora’s are named
- PERF-23 MUST Work driven by text the user types waits for typing to pause (a debounce) when it leaves the
FX thread or cannot finish within a frame: a search of files, a request to a server, a re-highlight. Filtering a
list already in memory, as a command palette does, is exempt and runs on every keystroke.
- Check (code): a listener on a text input’s text that starts background work, or work too long for one frame,
restarts a timer (a
PauseTransition’splayFromStart, or the app’s debounce helper) and the work runs when the timer fires; a listener that only filters or ranks an in-memory list needs none. - Reference: Editora
ui/SearchInFilesPopup.java(150 ms beforerunSearch),ui/SearchEverywherePopup.java(120 ms),ui/WorkspaceSymbolPopup.java(150 ms before the language server is asked) and, for the editor’s text,editor/SettledEditDispatcher.java, one timer that runs the re-highlight 150 ms after the last edit. Itsui/CommandPalette.javaandui/QuickOpen.javafilter their in-memory lists on every keystroke: the exempt case. Editora doesn’t hold the rule everywhere yet: the debugger’s completion (ui/DebugCompletion.java) asks the debug adapter again on every change of the field’s text while its list is open, with no timer, andui/FileFinder.javastarts reading a folder as soon as the typed path names another one.
- Check (code): a listener on a text input’s text that starts background work, or work too long for one frame,
restarts a timer (a
- PERF-07 MUST An app that shows a stream as it arrives (the output of a process, log records, progress or
readings from another thread) hands it to the FX thread in batches at least 16 ms apart, never one
runLaterper line or record.- Check (code): in an app that shows a stream, the thread that receives it appends to a buffer that the FX
thread drains, with a minimum interval of 16 ms or more between drains, or once a pulse (pulses come a frame
apart); no reader calls
Platform.runLateronce for each line or record. A stream is what arrives at its source’s pace, however many items that is: a process’s output, log records, the results of a scan handed over as each is found. A poll the app paces itself, one hand-over for each tick of a timer of 16 ms or more (a reading fetched every few seconds), already hands over that far apart and needs no buffer. An app whose FX thread is sent no stream, as one whose log window reads its store only when it opens or is refreshed, is not covered. - Reference: Editora
process/OutputPump.java(MIN_DRAIN_INTERVAL_MILLIS),ui/ConsoleAppender.java. Torrenta doesn’t yet for its event log: the bridge inui/EventLog.java(logBridge) hands each warning it catches to the FX thread in arunLaterof its own. nux doesn’t yet for its network scan:scaninservice/DiscoveryService.javahands each server it finds to the FX thread in arunLaterof its own; its poll hands over one reading every five seconds (service/PollService.java), which is paced already. Mirada’s Debug Log window (ui/DebugLogWindow.java) reads the log when it opens and on Refresh, so no log stream reaches its FX thread.
- Check (code): in an app that shows a stream, the thread that receives it appends to a buffer that the FX
thread drains, with a minimum interval of 16 ms or more between drains, or once a pulse (pulses come a frame
apart); no reader calls
- PERF-08 MUST Work only on what is visible and only on what changed: no O(document) or O(list) work per
keystroke, scroll or tick, and a list the user or the data can grow without a limit the app sets is shown in a
virtualized control (
ListView,TableView, a fixed cell size), which builds nodes for the visible rows only. Filtering a list already in memory, as a command palette does, is exempt and runs on every keystroke.- Check (code):
grep -rnE 'textProperty\(\)|KEY_(TYPED|PRESSED)|setOnKey|setOnScroll|vvalueProperty|AnimationTimer|Timeline|PauseTransition|scheduleAtFixedRate' src/main/javalists the first candidates: the listeners on text, keys and scrolling, and the timers. Each line is judged by reading what it runs on every keystroke, scroll or tick. It is fine when that handles the edited range or the visible rows, or filters or ranks a list already in memory. It is a violation when it reads, measures, styles or rebuilds the whole document or every item of a list. An editor’s own stream of changes is a text listener too (Editora’splainTextChanges), which the grep does not list.grep -rnE 'getChildren\(\)\.(add|addAll|setAll)\(' src/main/javalists the second: the lines that put nodes into a pane. It is a violation where a loop makes one node for each item of a list the user or the data can grow without a limit the app sets (results, log records, files, transfers), which belongs in aListVieworTableView; it is fine where the pane holds a set of controls the code fixes, or a list the app caps at a number it names (a bar of at most five preset chips). - Reference: Editora
editor/highlight/HighlightPass.java, which restyles only as far as an edit reaches. No app has been read through for the rule yet. Found so far, each a loop that makes a node for every item of a list nothing caps: Modula’s preset bar (a chip for each preset,rebuildinui/PresetBar.java); nux’s dashboard (a card for each saved profile it watches and for each UPS, rebuilt as readings arrive,setFleetandsetOverviewinui/Dashboard.java); Torrenta’s rule and tags dialogs (a check box for each feed and each tag,ui/RuleDialog.java,ui/TagsDialog.java); and Editora’s crontab preview and pull-request checks card (a node for each job and each check run,editor/structured/CrontabPreview.java,ui/ChecksListCard.java).
- Check (code):
- PERF-09 SHOULD A hot path allocates little: it reuses buffers and arrays, and caches data a repaint only
reads.
- Check (code): the per-frame and per-keystroke code allocates no new arrays or images when the size has not changed.
- Reference: Editora
editor/minimap/Minimap.java(the snapshot image reused at the same size),MinimapRows.java. The app template’s palette cells keep their text runs, chord chip and tooltip and relabel them as the query changes, making a new run only when a title needs more than the cell had (ui/Picker.java).
- PERF-10 SHOULD CSS stays cheap: no
applyCss()on a large subtree, stable style classes, and spans of the same style merged before they are applied.- Check (code):
applyCss()is called only on small nodes; style classes are not toggled per keystroke. - Reference: Editora
SpanMergerineditor/highlight/TextMateHighlighter.java,docs/gotchas.md. The app template’s palette draws a title as one text run per change of style, not a node per letter (ui/Picker.java).
- Check (code):
Memory and size
Section titled “Memory and size”- PERF-11 MUST Everything that grows is bounded: logs, histories, consoles, caches, undo. The newest is kept.
- Check (code): each store that grows while the app runs (a log, a history, a console’s text, a cache, an undo stack) has a named cap, and the code that adds to it drops the oldest entry once the cap is passed. A test that fills a store past its cap and finds the oldest dropped is the surest evidence.
- Reference: Editora
ui/MessageLog.java(200 entries, the oldest dropped;MessageLogTest),ui/DebugLog.java(2,000 records, the oldest dropped;DebugLogTest), andtest/OutputCap.java, which keeps the head and the tail of one test’s output (200,000 characters) with a note between them of how much was cut. The note is Editora’s choice, not part of the rule.
- PERF-12 MUST In an app that opens files or data the user picks, a large input is guarded before it loads:
its size is checked before its content is read, or the read is capped, and what will not fit is never read in.
The app refuses it with a message or opens only the part that fits. Where an input can open with less, without
features the app runs over its content, as a file in an editor can open without highlighting or a minimap, the
app steps down as the input grows: those features turn off past one threshold, and past another it opens
read-only or capped. An input the app can only read in or refuse (an imported theme, a
.torrentfile) has nothing to step down to.- Check (code): the code that loads a picked file or import compares its size against a named limit before reading the content, or reads through a cap, and refuses or cuts what passes the limit. Where the app runs features over an input’s content that the input can open without (an editor’s highlighting, its minimap), a lower named threshold turns them off and a higher one opens the input read-only or capped. Where it runs none, the size check or the cap is the whole of the rule.
- Reference: Editora, whose tiers are the example:
EditorBuffer.LARGE_FILE_BYTES(5 MB: no highlighting, no minimap) andHUGE_FILE_BYTES(50 MB: read-only and cut to 50 MB), andui/LoadHeapGuard.java, which caps a load at what the free heap affords (LoadHeapGuardTest). Termina’s theme import has nothing to step down to:importFileinui/Themes.javareads at most 8 MB andtheme/ThemeImport.javarefuses a file over 4 MB. Torrenta doesn’t yet for a.torrentfile the user picks:resolveinsession/Session.javareads it whole (Files.readAllBytes) without looking at its size.
- PERF-13 MUST A closed window releases what it held: listeners, timers, executors, file watchers, native
resources.
- Check (code): the code that runs when a window closes (its close or hide handler, or the dispose method that handler calls) stops every timer and animation the window started, shuts down every executor, thread and file watcher it owns, frees its native resources (a process, a socket, a file handle), and removes each listener it added to something that outlives it: the shared settings, a service, another window. A test that opens and closes windows and finds nothing left running is the surest evidence.
- Reference: Editora’s
MainController.disposeWindow, which shuts down each owner of a window’s workers in turn, one failure never skipping the rest (ui/WindowDisposal.java). Its tests:FxWindowFixtureLifecycleFxTest, which finds a disposed window’s workers shut down, andClosedLspManagers. The app template (WindowLifecycleFxTest), Termina (WindowLifecycleTest) and Mirada (ClosedWindowTest) have such a test too.
Start-up
Section titled “Start-up”- PERF-14 MUST The first frame comes first: only what the first window shows is built before it. Everything
else builds on first open: a closed panel’s content, the Settings pages, the dialogs and the other windows.
- Check (code): the code that builds the first window (
start(), and the main window’s constructor and what it calls) makes only what that window shows: no Settings window or page, no dialog, no other window and, in an app with tool panels, no closed panel’s content. Each of those is made by the code that first opens it, through a supplier or a field filled on first use. A test that opens the first window and finds none of them built is the surest evidence. - Reference: Editora’s lazy
ToolWindowsuppliers, and its Settings pages, built on the firstshow(ui/SettingsWindow.java).LazyToolWindowsFxTestasserts the tool-panel part: no closed tool window has built its panel. Editora doesn’t hold the rule in one place yet: it builds the shared Output console (buildOutput), an empty tab pane, with the window, because every build writes to it while it is closed, and the test leaves that panel out. The template’sStartupDeferralFxTestand Mirada’sStartupDeferralTestassert it for their first windows. Torrenta doesn’t yet: the constructor of its main window makes the Log, the Statistics and the Settings windows (new LogWindow,new StatisticsWindow,new SettingsWindowinui/MainWindow.java).
- Check (code): the code that builds the first window (
- PERF-15 MUST What nobody waits for starts after the first frame has painted: the update check, extra
fonts, indexes and caches.
- Check (code): the update check, the loading of fonts the first window does not draw with, and the building
of indexes and caches start from a callback that runs once the first frame has painted (a pulse after the
window is shown, as Editora’s
loadRemainingAfterNextPaintwaits for), never frommain,init()or the body ofstart(). A test that finds the deferred work not started before the first paint is the surest evidence. - Reference: Editora
ui/UpdateCheckScheduler.java,Fonts.loadRemainingAfterNextPaint(UpdateCheckSchedulerTest,FontsDeferredLoadFxTest,StartupDeferralFxTest). The template (FirstPaint.theninui/Startup.java), Termina (FirstFrame.afterin itsApp.java) and Mirada (afterFirstPaintinui/ViewerWindow.java) defer theirs the same way. Modula and nux don’t yet: each starts its update check in the body ofstart()(checkForUpdatesinModulaApp.java,maybeCheckForUpdatesin nux’sApp.java).
- Check (code): the update check, the loading of fonts the first window does not draw with, and the building
of indexes and caches start from a callback that runs once the first frame has painted (a pulse after the
window is shown, as Editora’s
- PERF-16 SHOULD The config read starts on a thread of its own before the toolkit does, so the two overlap
and the wait for it that PERF-01 allows at start-up,
start()taking the result, is short. An app whosestart()loads its settings itself does not meet this, whether or notmainread the file earlier.- Check (code):
mainstarts the config read on its own thread beforelaunch, from an entry point that is not theApplicationsubclass (the launcher starts the toolkit for one before itsmainruns), andstart()takes that read’s result instead of reading the files itself. A loadstart()makes only when the earlier read failed is a fallback and passes. - Reference: Editora’s
config-prefetchthread inApp.java(prefetchConfig, joined once bytakeBootstrap), entered throughLauncher.java. Mirada’ssettings-readthread in itsApp.java(readSettings, joined bysettings()) does the same in the native image, which enters throughLauncher; its jlink image’s main class isAppitself, so there the toolkit is up before the read starts. Termina reads its settings inApplication.init()(preparein itsApp.java): off the FX thread, sostart()waits for nothing, but after the toolkit has started. The app template meets it: itsMain.java, not theApplicationsubclass, startsStartup.readAheadon a thread of its own beforelaunch, andApp.inittakes the result (takePreparedinui/Startup.java), sostart()reads no settings file. Torrenta (App.java), Modula (ModulaApp.java) and nux (App.java, which also reads the file once inmainfor the language) load their settings insidestart(). Torrenta’smainreads the file once as well, on the main thread, for its tray and badge settings.
- Check (code):
- PERF-17 SHOULD The app ships precompiled stylesheets (
.bss). The AOT cache, the other half of a fast start, is REL-10.- Check (code): the build converts the app’s
.cssfiles to.bss, and the packaged app carries them. - Reference: Editora
scripts/css2bss.java, run by thecss-to-bssexecution inpom.xml. The app template’sdistprofile runs itsui/StyleCompiler.javaover the built stylesheets, which writes a.bssbeside each.css, andui/Themes.javaloads the.bsswhere there is one (StyleCompilerTest). No other app converts its own stylesheets yet.
- Check (code): the build converts the app’s
Measure, don’t guess
Section titled “Measure, don’t guess”- PERF-18 SHOULD Every change on a hot path says what it costs in its pull request: added FX-thread work,
allocation per keystroke or scroll, extra layout passes, memory. “Negligible” is an answer; no answer is not.
- Check (by hand): read the app’s recent pull requests that touch a hot path.
- Reference: Editora
docs/performance.md(its opening paragraph).
- PERF-19 SHOULD Start-up is measured by a script that takes the median of several cold launches, and by
phase marks in the app.
- Check (code): the repository has the script, and
mainand the first paint record phase marks. - Reference:
scripts/measure-startup.shin Editora, Termina, Mirada and the app template, whose marks are recorded byStartupMarks.javafrommainand the first paint; Editoraperf/Startup.java.
- Check (code): the repository has the script, and
- PERF-20 SHOULD The app can sample its FX thread when something stalls.
- Check (code): an environment variable or property turns on a sampler of the FX thread’s stack.
- Reference: Editora
perf/Startup.java(EDITORA_PERF_SAMPLE=1, withEDITORA_PERF=1); Miradaperf/FxSampler.java(MIRADA_PERF_SAMPLE=1); the app template’sui/FxSampler.java(-Dexampleapp.fxSampler=<ms>orEXAMPLEAPP_FX_SAMPLER, logging the FX thread’s stack on a stall;FxSamplerTest).
- PERF-21 SHOULD Each hot path that once regressed keeps a headless test.
- Check (test): the fix for a hot-path regression adds a headless test that fails on the old code.
- Reference: Editora
MinimapDeferredRenderFxTest.
- PERF-22 SHOULD A suspected regression gets a number before and after, from temporary
System.nanoTimeinstrumentation if nothing better exists.- Check (by hand): the pull request that fixes it states both numbers.
- Reference: Editora
docs/performance.md.
Pauta 6.1.0 · · Changelog · Permanent link to this page in 6.1.0