From 73f9f3c00809ce793f34bbd4a367e02b8d46d304 Mon Sep 17 00:00:00 2001 From: Charlie Marsh Date: Sun, 27 Sep 2026 11:02:17 -0400 Subject: [PATCH] Reduce memory used by diagnostics --- crates/ruff_db/src/diagnostic/mod.rs | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/crates/ruff_db/src/diagnostic/mod.rs b/crates/ruff_db/src/diagnostic/mod.rs index a39fb593c6cf35..2acd785ad1c73d 100644 --- a/crates/ruff_db/src/diagnostic/mod.rs +++ b/crates/ruff_db/src/diagnostic/mod.rs @@ -145,7 +145,13 @@ impl Diagnostic { /// should be constructed via [`Annotation::primary`]. A diagnostic with no /// primary annotations is allowed, but its rendering may be sub-optimal. pub fn annotate(&mut self, ann: Annotation) { - Arc::make_mut(&mut self.inner).annotations.push(ann); + let annotations = &mut Arc::make_mut(&mut self.inner).annotations; + // Most diagnostics have exactly one annotation. Avoid the default allocation of four + // annotations on the first push, while retaining normal amortized growth thereafter. + if annotations.is_empty() { + annotations.reserve_exact(1); + } + annotations.push(ann); } /// Adds an "info" sub-diagnostic with the given message. @@ -172,9 +178,11 @@ impl Diagnostic { /// Adds an "info" sub-diagnostic before any existing sub-diagnostics. pub fn prepend_info<'a>(&mut self, message: impl IntoDiagnosticMessage + 'a) { - Arc::make_mut(&mut self.inner) - .subs - .insert(0, SubDiagnostic::new(SubDiagnosticSeverity::Info, message)); + let subs = &mut Arc::make_mut(&mut self.inner).subs; + if subs.is_empty() { + subs.reserve_exact(1); + } + subs.insert(0, SubDiagnostic::new(SubDiagnosticSeverity::Info, message)); } /// Adds a "help" sub-diagnostic with the given message. @@ -190,7 +198,11 @@ impl Diagnostic { /// to it. For the simpler case of a sub-diagnostic with only a message, /// using a method like [`Diagnostic::info`] may be more convenient. pub fn sub(&mut self, sub: SubDiagnostic) { - Arc::make_mut(&mut self.inner).subs.push(sub); + let subs = &mut Arc::make_mut(&mut self.inner).subs; + if subs.is_empty() { + subs.reserve_exact(1); + } + subs.push(sub); } /// Return a `std::fmt::Display` implementation that renders this @@ -685,6 +697,9 @@ impl SubDiagnostic { /// to have no annotations (e.g., a simple note) than for a diagnostic to /// have no annotations. pub fn annotate(&mut self, ann: Annotation) { + if self.inner.annotations.is_empty() { + self.inner.annotations.reserve_exact(1); + } self.inner.annotations.push(ann); }