Skip to content

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

Merged
UziTech merged 1 commit into
markedjs:masterfrom
hong4rc:perf/linear-inline-masking
Jul 15, 2026
Merged

fix: Avoid O(n^2) masked source rebuild in inline tokenizer#4017
UziTech merged 1 commit into
markedjs:masterfrom
hong4rc:perf/linear-inline-masking

Conversation

@hong4rc

@hong4rc hong4rc commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

While looking for remaining quadratic paths after #4013/#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 #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.

@vercel

vercel Bot commented Jul 13, 2026

Copy link
Copy Markdown

@hong4rc is attempting to deploy a commit to the MarkedJS Team on Vercel.

A member of the Team first needs to authorize it.

@vercel

vercel Bot commented Jul 13, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
marked-website Ready Ready Preview, Comment Jul 13, 2026 2:55pm

Request Review

@UziTech UziTech left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work! 💯

@UziTech
UziTech requested review from calculuschild and styfle July 14, 2026 22:27

@calculuschild calculuschild left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Woo nice. Very good find!

@UziTech
UziTech merged commit 9154f8f into markedjs:master Jul 15, 2026
8 checks passed
github-actions Bot pushed a commit that referenced this pull request Jul 21, 2026
## [18.0.7](v18.0.6...v18.0.7) (2026-07-21)

### Bug Fixes

* Avoid O(n^2) backtracking in HTML block close and tilde interrupt regexes ([#4014](#4014)) ([f945fc5](f945fc5)), closes [#3991](#3991)
* Avoid O(n^2) masked source rebuild in inline tokenizer ([#4017](#4017)) ([9154f8f](9154f8f))
* keep empty list after blockquote as a sibling block ([#4004](#4004)) ([3f144a0](3f144a0))
* preserve code spans adjacent to tildes ([#4012](#4012)) ([0de7188](0de7188))
* Recognize setext headings whose first line starts with # ([#4015](#4015)) ([f056437](f056437)), closes [#1](#1)
* treat a line of only tabs as a blank line between paragraphs ([#4007](#4007)) ([bc2f121](bc2f121))
@anthon

anthon commented Jul 21, 2026

Copy link
Copy Markdown

A quick note here: @UziTech, would it make sense to chain a conditional to the maskedSrc.replace(..), or otherwise catch an undefined/non-string first param to inline|parseInline?

Pardon the post-close comment. Let me know if I should file a proper issue.

@UziTech

UziTech commented Jul 21, 2026

Copy link
Copy Markdown
Member

@anthon I think the correct thing to do if the first parameter is not a string would be to throw an error. That seems to already happen in this case.

@anthon

anthon commented Jul 21, 2026

Copy link
Copy Markdown

You're right. Previously it failed silently, which I thought was elegant render-library design; no input no output. cannot call method "replace" of undefined with nested lexers and a minified import is fairly tricky to debug, but if throwing is the plan, then 👍.

Anyway – thanks for great work!

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.

4 participants