Skip to content

fix: Avoid O(n^2) masked source rebuild in inline tokenizer#4

Closed
hong4rc wants to merge 1 commit into
masterfrom
perf/linear-inline-masking
Closed

fix: Avoid O(n^2) masked source rebuild in inline tokenizer#4
hong4rc wants to merge 1 commit into
masterfrom
perf/linear-inline-masking

Conversation

@hong4rc

@hong4rc hong4rc commented Jul 13, 2026

Copy link
Copy Markdown
Owner

While looking for remaining quadratic paths after markedjs#4013/markedjs#4014, I found that the link-masking step in Lexer.tokenize is O(n²) on some ordinary inputs.

Before em/strong processing, tokenize masks out reflinks, escaped characters, and other inline blocks so they don't interfere. Each of the three masks ran a while ((match = rule.exec(maskedSrc))) loop that rebuilt the entire maskedSrc string on every match:

while ((match = this.tokenizer.rules.inline.anyPunctuation.exec(maskedSrc)) !== null) {
  maskedSrc = maskedSrc.slice(0, match.index) + '++' + maskedSrc.slice(...lastIndex);
}

For an input with k matches that's k full-length string rebuilds — O(k·n), i.e. quadratic when the matches are dense. It's easy to hit with perfectly normal markdown: a paragraph full of escaped punctuation, many inline `code` spans, or many reference-style [ref] links. On my machine (marked.parse at HEAD):

input time
'\\.'.repeat(100000) ~2.4 s
'`x` '.repeat(60000) ~1.6 s
'[a]: x\n\n' + '[a] '.repeat(100000) ~4.3 s

The masking regexes match linearly on their own — the cost is purely the repeated slice+concat rebuild, not the regex. This is the string-rebuild sibling of the em-mask work in markedjs#2818 (which fixed the regex side).

The fix replaces each hand-rolled loop with a single-pass String.prototype.replace, so the masked string is built once instead of k times. Every replacement is exactly the same length as what it replaces (reflink → [ + a×(len−2) + ], escapes → ++, blockSkip → context prefix + same-length padding), so the global regex's lastIndex bookkeeping is unaffected and the output is byte-identical — the whole spec suite (CommonMark, GFM, original, redos) passes unchanged. The three inputs above drop to ~5 ms / ~40 ms / ~68 ms and scale linearly.

I added test/specs/redos/quadratic_inline_masking.cjs covering the three shapes; each exceeds the redos harness's 1-second budget on master and passes with this change.

@hong4rc

hong4rc commented Jul 13, 2026

Copy link
Copy Markdown
Owner Author

Superseded by upstream markedjs#4017

@hong4rc hong4rc closed this Jul 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant