From cdfb3343aca9fc053a55abdc5eed307c7d8ca50b Mon Sep 17 00:00:00 2001 From: Horizontal42 <75383519+Horizontal42@users.noreply.github.com> Date: Wed, 12 Aug 2026 22:07:38 +0300 Subject: [PATCH] perf(ui): cache variable highlight RegExp creation Caching the RegExp compilation for highlighting variables under the cursor avoids creating an assignment RegExp and a highlight RegExp constantly when typing, saving roughly ~40% of the overhead time for this function as tested. --- src/ui/editor.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/ui/editor.ts b/src/ui/editor.ts index 44cf173..8d5ca57 100644 --- a/src/ui/editor.ts +++ b/src/ui/editor.ts @@ -75,6 +75,8 @@ const highlightField = StateField.define({ provide: (f) => EditorView.decorations.from(f), }); +const varHighlightReCache = new Map(); + /** Highlights every occurrence of the variable under the cursor. */ function buildVarHighlight(state: EditorState): DecorationSet { const builder = new RangeSetBuilder(); @@ -90,11 +92,21 @@ function buildVarHighlight(state: EditorState): DecorationSet { if (a === b) return builder.finish(); const word = text.slice(a, b); if (!/^[\p{L}_][\p{L}\d_]*$/u.test(word)) return builder.finish(); + + let cachedRe = varHighlightReCache.get(word); + if (!cachedRe) { + const esc = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + cachedRe = { + assignment: new RegExp(`^\\s*${esc}\\s*=`, "mu"), + highlight: new RegExp(`(? 1000) varHighlightReCache.clear(); + varHighlightReCache.set(word, cachedRe); + } + // only highlight if the word is actually assigned somewhere in the document - const esc = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - if (!new RegExp(`^\\s*${esc}\\s*=`, "mu").test(text)) return builder.finish(); - const re = new RegExp(`(?