From 722fffa96fe2ff1d32408aa6c3e782736d3d3fd2 Mon Sep 17 00:00:00 2001 From: camc314 <18101008+camc314@users.noreply.github.com> Date: Sun, 28 Dec 2025 05:00:19 +0000 Subject: [PATCH] perf(codegen): restructure print_comments to avoid index comparisons in loop (#17402) The idea is that this is a hot-ish path, so if we can remove the index checks from within the hot loop, it should be faster --- crates/oxc_codegen/src/comment.rs | 61 +++++++++++++++++++------------ 1 file changed, 38 insertions(+), 23 deletions(-) diff --git a/crates/oxc_codegen/src/comment.rs b/crates/oxc_codegen/src/comment.rs index d96f732bd3480..1ed404fb68f78 100644 --- a/crates/oxc_codegen/src/comment.rs +++ b/crates/oxc_codegen/src/comment.rs @@ -85,40 +85,55 @@ impl Codegen<'_> { } pub(crate) fn print_comments(&mut self, comments: &[Comment]) { - for (i, comment) in comments.iter().enumerate() { - if i == 0 { - if comment.preceded_by_newline() { - // Skip printing newline if this comment is already on a newline. - if let Some(b) = self.last_byte() { - match b { - b'\n' => self.print_indent(), - b'\t' => { /* noop */ } - _ => { - self.print_hard_newline(); - self.print_indent(); - } - } + let Some((first, rest)) = comments.split_first() else { + return; + }; + + if first.preceded_by_newline() { + // Skip printing newline if this comment is already on a newline. + if let Some(b) = self.last_byte() { + match b { + b'\n' => self.print_indent(), + b'\t' => { /* noop */ } + _ => { + self.print_hard_newline(); + self.print_indent(); } - } else { - self.print_indent(); } } - if i >= 1 { + } else { + self.print_indent(); + } + self.print_comment(first); + + if let Some((last, middle)) = rest.split_last() { + for comment in middle { if comment.preceded_by_newline() { self.print_hard_newline(); self.print_indent(); } else if comment.is_legal() { self.print_hard_newline(); } + self.print_comment(comment); } - self.print_comment(comment); - if i == comments.len() - 1 { - if comment.is_line() || comment.followed_by_newline() { - self.print_hard_newline(); - } else { - self.print_next_indent_as_space = true; - } + + if last.preceded_by_newline() { + self.print_hard_newline(); + self.print_indent(); + } else if last.is_legal() { + self.print_hard_newline(); } + self.print_comment(last); + + if last.is_line() || last.followed_by_newline() { + self.print_hard_newline(); + } else { + self.print_next_indent_as_space = true; + } + } else if first.is_line() || first.followed_by_newline() { + self.print_hard_newline(); + } else { + self.print_next_indent_as_space = true; } }