Skip to content

Serializing many adjacent attention nodes is quadratic #96

Closed

Description

@etrepum

Initial checklist

Affected package

mdast-util-to-markdown@2.2.2 (also 2.2.0 and 2.2.1)

Steps to reproduce

import {toMarkdown} from 'mdast-util-to-markdown'

for (const n of [100, 200, 400, 800]) {
  const children = []
  for (let i = 0; i < n; i++) {
    const c = i % 2 ? '.' : 'a'
    const d = i % 2 ? 'a' : '.'
    children.push({type: 'strong', children: [{type: 'text', value: c}]})
    children.push({
      type: 'emphasis',
      children: [
        {type: 'text', value: d},
        {type: 'strong', children: [{type: 'text', value: c}]}
      ]
    })
  }
  const start = performance.now()
  toMarkdown({type: 'root', children: [{type: 'paragraph', children}]})
  console.log(n, Math.round(performance.now() - start), 'ms')
}

Actual behavior

100 261 ms
200 838 ms
400 3046 ms
800 12733 ms

In lib/util/container-phrasing.js, serialize fixes one mistake at a time. Here a mistake is two sequences that touch and join into one run, such as **a** followed by *…. The paragraph above has about one mistake per three nodes. For each mistake, improve tries the other sequences of each candidate (around six tries here), and every try calls render and check over the whole paragraph. candidates also walks all tokens. That makes the work proportional to the number of mistakes times the paragraph length. A paragraph that sits inside a larger attention node pays this again, once for the inner serialize and once for the outer one, because each starts with an empty chosen.

Text editors that export to markdown hit this with paragraphs of short, alternately formatted runs, for example pasted rich text, which is how we found it (@lexical/mdast's markdown export).

Expected behavior

Time grows linearly with the number of nodes.

Runtime

node@22.23.4

Package manager

pnpm

Operating system

Linux

Build and bundle tools

N/A

Activity

  1. added
    👋 phase/new
    🤞 phase/open
    and removed
    👋 phase/new
    on Nov 3, 2026
  2. github-actions commented on Nov 6, 2026

    @github-actions
  3. removed
    🤞 phase/open
    on Nov 6, 2026
  4. wooorm commented on Nov 6, 2026

    @wooorm
    Member

    2.2.3, thanks!

  5. etrepum commented on Nov 6, 2026

    @etrepum
    Author

    Thank you for the quick fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    💪 phase/solved

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions