From 5efedb044d364cf1341f0c3c8c0ddd47333b7abf Mon Sep 17 00:00:00 2001 From: Raing5Days Date: Tue, 17 Nov 2026 11:32:21 +0800 Subject: [PATCH] perf(editor): skip the fence regex when an inline reply cannot match it sanitizeInlineAiMarkdownResponse entered the regex engine for every inline reply. The pattern is anchored at both ends, so the engine starts a match attempt at every position even though only a leading fence can ever match, and the pattern literal was rebuilt at the call site on every call. The pattern and its only possible first character are module constants now, and a reply that does not open with a backtick returns the trimmed text directly. Behaviour is unchanged: a fenced reply with or without a language tag, and a reply with no fence, all produce the same string as before. Measured with the local OpCase benchmark for this module over 200,000 repetitions per cycle: 0.078 us/call -> 0.040 us/call (worst call 0.044 us) against a 0.0548 us/call budget, which is 70% of the pre-change median. The number is module cost, not a frame time. Testing: src/tools/editor/meditor/utils/inlineAi.test.ts (3 passed). --- .../src/tools/editor/meditor/utils/inlineAi.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/web-ui/src/tools/editor/meditor/utils/inlineAi.ts b/src/web-ui/src/tools/editor/meditor/utils/inlineAi.ts index 10958d3e45..d14a48a2d1 100644 --- a/src/web-ui/src/tools/editor/meditor/utils/inlineAi.ts +++ b/src/web-ui/src/tools/editor/meditor/utils/inlineAi.ts @@ -376,13 +376,24 @@ export function buildInlineTodoPrompt(params: InlineAiPromptParams): string { return buildInlineInsertPrompt(params, 'todo'); } +const FENCE_PATTERN = /^```(?:markdown|md)?\s*([\s\S]*?)\s*```$/i; +const FENCE_CHAR = 0x60; // '`' + export function sanitizeInlineAiMarkdownResponse(value: string): string { const trimmed = value.trim(); if (!trimmed) { return ''; } - const fencedMatch = trimmed.match(/^```(?:markdown|md)?\s*([\s\S]*?)\s*```$/i); + // A fenced reply is the exception, not the rule, and entering the regex engine for every + // streamed response costs more than the rest of this function: String.match builds its + // match state even on a first-character mismatch. The pattern can only match a string that + // opens with a fence, so anything else returns the trimmed text directly. + if (trimmed.charCodeAt(0) !== FENCE_CHAR) { + return trimmed; + } + + const fencedMatch = trimmed.match(FENCE_PATTERN); if (fencedMatch) { return fencedMatch[1].trim(); }