Файли
openidea/src/workbench/perfProbe.ts
T
l0ng-ai 5804fcad16 perf: speed up Angular typing, Git Log, console output and start-up; measure more interactions (#1901)
* perf(project-tree): measure row widths once per frame

The horizontal scroll range was measured in a layout effect on every render:
each pass forced layout, its setState re-rendered synchronously and measured
again, and the ResizeObserver was recreated each time, firing once more.
Expanding a 10k-entry folder went from ~26 ms to ~63 ms.

Keep one observer per tree and coalesce renders and resizes into a single
measurement on the next animation frame. Expanding is back to ~30 ms and
arrow-key p50 drops from 3.3 ms to 1.7 ms; the widths behave as before.

* perf(github): load the pull requests integration after start-up

Actions, the tool window and the timeline editor stay registered at start-up;
their implementations, the connection and review-mode tracking load on idle
or on first use. Takes ~60 KB gzip off the initial bundle.

* perf(templates): load Emmet when an HTML or stylesheet editor opens

The Emmet engine (~70 KB minified) was part of the initial bundle; it now loads
with the first editor that can expand abbreviations, or with Update Tag with Emmet.

* perf(search, run): load popups and Edit Configurations when first shown

Search Everywhere, Find in Files, the recent files/locations popups, File
Structure and the Run/Debug Configurations dialog were part of the initial
bundle although each only renders while open. `lazyWhen` mounts a lazy view
only while its condition holds; the idle prefetch still loads them right after
start-up, so opening one stays as fast.

* perf: load dialogs, the SQL console and diff views on first use

- Database dialogs, Assign Shortcut and the Logcat tool window load when shown.
- The SQL console extensions load with the first SQL editor
  (`lazyEditorExtension` reconfigures the editor once they arrive).
- The changes tree loads the diff viewer when a file is selected, and
  "Open Repository Log" loads the revision browser when run.

* perf: load plugin, debugger and project popups when first shown

The IntelliJ theme import, the debugger's popovers and dialogs and the title
bar's project popup now load when first opened. `lazyWhen` keeps a view
mounted once shown, so its own open/closed handling is unchanged.

* perf(angular): parse only text with Angular syntax as Angular

Every text node of a template got its own nested Angular parse, including
the whitespace between tags, which is most of them. Text without a `{`, `}`
or `@` holds no interpolation or block, so it stays HTML text. A full parse
of a 12k-line template takes about a fifth less work.

* perf(angular): reuse nested trees of unchanged text and attributes

An edit makes the mixed parser recreate many text and attribute nodes it
does not keep: the document's own text and the nodes up to the viewport. It
reuses nested trees only of nodes it kept, so each of those was parsed again
as Angular on every keystroke (~170 nested parses per key in a 12k-line
template). Their parse depends only on their text, so the trees are now
remembered by text, up to about 2M characters.

Typing in the middle of a 12k-line template: main thread per key 57 -> 22 ms,
p50 latency 30 -> 19.5 ms, no long tasks.

* perf: budget typing in a large Angular template

* perf: measure code completion over a 2,000-item list

The harness's probe can answer completion with generated items through the
command route; language server requests go through a route when one is
installed, not only under Tauri. The scenario opens the popup by typing,
narrows it letter by letter and moves the selection, with budgets for each.

* perf(run): show a flood of console output at most every 50 ms

While a process printed thousands of lines a second, the Run console
appended, re-rendered and laid out on every frame, so typing in an editor
meanwhile missed the next frame 35% of the time. A line after a quiet spell
still shows on the next frame; a flood now updates the console at ~20 Hz,
and typing during it misses 2-5% (p50 16 -> 9.7 ms) with the output done as
fast as before.

The performance harness gets a scenario for it: 50,000 log lines at 200 a
frame (a dev and perf build action, run.sampleOutput) while typing.

* perf(vcs): keep Git Log rows from re-rendering on every selection change

Commit rows were memoized but received a new Set and new closures on every
render, so moving the selection re-rendered every visible row, and each row
built a new Intl.DateTimeFormat for its date. Rows now get stable handlers and
shared remote-name sets, and date formatting reuses cached formatters.

* perf: measure the Git Log and splitter dragging

gitLog shows 20k generated commits served page by page through a fake vcs_log,
walks the selection with the arrow keys and wheel-scrolls the list.
resizePanels drags the side and bottom splitters with an editor, the Project
tree and the Log open. The perf probe's fake backends can now be combined.

* perf: translate the sample output action and keep fake completion details out of the text catalog

* perf(vcs): keep Git Log scrolling smooth as pages load

Each page of the log recomputed hidden long edges by scanning every row once per
lane, and the store laid out the whole graph a second time for fields nothing
read. Long edges are now found in one pass over the rows, the unused store graph
is gone, and the next page is requested while a page of rows is still ahead so
fast scrolling doesn't reach the end before git answers. The commit list also
contains its layout, so rows entering while scrolling no longer relay out the
workbench.

* perf: load the Git Log scenario's pages with git's latency and scroll across several
2026-11-07 10:56:59 +08:00

190 рядки
7.2 KiB
TypeScript

/**
* Hooks for the performance harness (`perf/`), exposed as `window.__openideaPerf`.
* Loaded only in dev and in `vite build --mode perf`; release builds never
* include it. Measurement itself lives in the harness so it stays out of the app.
*/
import { syntaxParserRunning } from "@codemirror/language";
import { executeAction } from "@/platform/actions";
import { bindingsFor } from "@/platform/keymap";
import { activeEditor } from "@/editor/api";
import { docBackend, type MemoryBackend } from "@/editor/core/backend";
import type { Commit, CompletionItem, CompletionKind, LogQuery } from "@/bindings";
import { setInvokeRoute } from "@/platform/tauriCore";
import { editorService } from "./contributions";
export interface PerfProbe {
/** Seeds file contents for the in-memory document backend (plain-browser mode). */
seed(path: string, text: string): void;
openFile(path: string): Promise<void>;
runAction(id: string, arg?: unknown): Promise<boolean>;
/** Effective keymap bindings of an action, e.g. `["Ctrl+Shift+A"]`. */
bindings(id: string): string[];
/** Moves the caret of the active editor and focuses it. */
setCursor(offset: number): void;
/** True while the active editor's background syntax parser still has work. */
parsing(): boolean;
/** Document length and caret of the active editor. */
editorState(): { path: string; length: number; lines: number; head: number } | null;
/**
* Answers code completion with `items` generated items (a language server's
* list); other language server requests report no server. `0` removes it.
*/
fakeCompletion(items: number): void;
/**
* Answers the Git Log with `commits` generated commits (a main line with
* feature branches merging into it), paged like the backend, each page after
* `latencyMs` (a `git log` call). `0` commits removes it.
*/
fakeGitLog(commits: number, latencyMs?: number): void;
}
const KINDS: CompletionKind[] = [
"method",
"function",
"field",
"variable",
"class",
"interface",
"property",
"keyword",
];
// Completion details as a language server reports them (code, not UI text).
const RESULT = "Promise<Result<Order>>";
const qualified = (name: string) => ["com", "acme", name].join(".");
function completionItem(i: number): CompletionItem {
const kind = KINDS[i % KINDS.length]!;
// Shared prefixes so typing narrows the list gradually, like real symbols.
const label = `${["get", "set", "create", "update", "find", "to", "is", "on"][i % 8]}${["Order", "Item", "Customer", "Invoice", "Payment", "Status"][(i >> 3) % 6]}${i}`;
return {
label,
labelDetail: kind === "method" || kind === "function" ? "(id: string, options?: Options)" : null,
detail: kind === "class" || kind === "interface" ? qualified(label) : RESULT,
kind,
documentation: null,
sortText: String(i).padStart(5, "0"),
filterText: null,
preselect: false,
deprecated: i % 97 === 0,
insertText: label,
isSnippet: false,
replaceRange: null,
replaceRangeTab: null,
additionalEdits: [],
commitCharacters: [],
command: null,
data: null,
server: 1,
};
}
function commit(i: number, count: number): Commit {
const id = (n: number) => n.toString(16).padStart(40, "0");
// Newest first: parents have higher indices. Every 12th commit merges a branch
// started 7 commits back; every third commit skips ahead, keeping a few lanes open.
const merge = i % 12 === 0 && i + 7 < count;
const next = i % 3 === 2 && i + 3 < count ? i + 3 : i + 1;
const parents = i + 1 >= count ? [] : merge ? [id(i + 1), id(i + 7)] : [id(next)];
const time = Date.UTC(2026, 10, 5) - i * 3_600_000;
const summary = `${["feat", "fix", "refactor", "test"][i % 4]}(orders): ${merge ? "merge" : "update"} order flow step ${i}`;
return {
id: id(i),
shortId: id(i).slice(-8),
parents,
author: ["Ada Lovelace", "Linus Torvalds", "Grace Hopper", "Ken Thompson"][i % 4]!,
email: `dev${i % 4}@acme.dev`,
committer: "CI",
committerEmail: "[email protected]",
timeMs: time,
commitTimeMs: time,
summary,
message: summary,
messageTruncated: false,
refs: i === 0 ? ["HEAD -> main", "origin/main"] : i % 250 === 0 ? [`tag: v1.${count - i}`] : [],
};
}
type Route = (cmd: string, args: unknown) => Promise<unknown> | null;
const routes = new Map<string, Route>();
/** Installs (or with `null` removes) one fake backend; the first that answers a command wins. */
function setRoute(name: string, next: Route | null) {
if (next) routes.set(name, next);
else routes.delete(name);
setInvokeRoute(
routes.size
? (cmd, args) => {
for (const r of routes.values()) {
const answer = r(cmd, args);
if (answer) return answer;
}
return null;
}
: null,
);
}
export function installPerfProbe(): () => void {
const probe: PerfProbe = {
seed(path, text) {
const backend = docBackend() as Partial<MemoryBackend>;
if (!backend.files) throw new Error("seed() needs the in-memory backend");
backend.files.set(path, text);
},
openFile: (path) => editorService().openFile(path),
runAction: (id, arg) => executeAction(id, arg),
bindings: (id) => bindingsFor(id),
setCursor(offset) {
const view = activeEditor()?.view;
if (!view) throw new Error("no active editor");
view.dispatch({ selection: { anchor: Math.min(offset, view.state.doc.length) }, scrollIntoView: true });
view.focus();
},
parsing() {
const view = activeEditor()?.view;
return !!view && syntaxParserRunning(view);
},
fakeCompletion(count) {
const items = Array.from({ length: count }, (_, i) => completionItem(i));
setRoute(
"completion",
count
? (cmd, args) => {
if (cmd === "lsp_completion") return Promise.resolve({ isIncomplete: false, items });
if (cmd === "lsp_resolve_completion") return Promise.resolve((args as { item: CompletionItem }).item);
if (cmd.startsWith("lsp_"))
return Promise.reject({ kind: "unavailable", message: "No language server available" });
return null;
}
: null,
);
},
fakeGitLog(count, latencyMs = 0) {
const commits = Array.from({ length: count }, (_, i) => commit(i, count));
setRoute(
"gitLog",
count
? (cmd, args) => {
if (cmd !== "vcs_log") return null;
const { skip, limit, range } = (args as { query: LogQuery }).query;
// Outgoing commits (`@{u}..HEAD`) and the like: none.
if (range) return Promise.resolve([]);
const page = commits.slice(skip, limit ? skip + limit : undefined);
return new Promise((resolve) => setTimeout(() => resolve(page), latencyMs));
}
: null,
);
},
editorState() {
const e = activeEditor();
if (!e) return null;
const { doc, selection } = e.view.state;
return { path: e.ctx.path, length: doc.length, lines: doc.lines, head: selection.main.head };
},
};
const w = window as unknown as { __openideaPerf?: PerfProbe };
w.__openideaPerf = probe;
return () => void delete w.__openideaPerf;
}