perf(formatter_markdown): pre-allocate the IR buffer (#27333)

Measured on 19,487 real-world Markdown files (mdn content, oxc-ecosystem-ci repos):

- IR elements / source bytes: median 0.29, p95 0.40, p98 0.46
- `0.4x` alone covers 94.9% of files without reallocation
  - With the 1024 floor, 97.6% (small documents have a higher ratio)
- `0.5x` would reach 99.5%, but over-allocates 96% of the used size instead of 66%
This commit is contained in:
leaysgur committed 2026-10-05 05:13:53 +00:00
1 parent 7d0e54dc20
commit 72f42a3efc
1 file changed
+4 -2
+4 -2
View File
@@ -59,8 +59,10 @@ pub fn format_with_session<'a>(
// A root `Document` owns a fresh Tailwind class scope (a fenced code block's classes join it)
let session = session.with_new_tailwind_scope();
let mut state = FormatState::new_with_session(context, session.clone());
// TODO: Pre-allocate
let mut buffer = VecBuffer::new(&mut state);
// Pre-allocate: measured on 19,487 real-world files (mdn content, oxc-ecosystem-ci repos),
// 0.4x source bytes plus a 1024-element floor for small documents avoids reallocation for 97.6% of the corpus.
let capacity = (parsed.source.len() * 2 / 5).max(1024);
let mut buffer = VecBuffer::with_capacity(capacity, &mut state);
write!(&mut buffer, FormatMarkdownRoot { parsed: &parsed });