Skip to content

Commit bca0279

Browse files
committed
Optimize indentation in the pretty printer.
Currently the pretty-printer calls `write!` for every space of indentation. On some workloads the indentation level can exceed 100, and a faster implementation reduces instruction counts by up to 7% on a few workloads.
1 parent 4c27fb1 commit bca0279

File tree

1 file changed

+21
-3
lines changed

1 file changed

+21
-3
lines changed

src/libsyntax/print/pp.rs

+21-3
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,9 @@ impl Default for BufEntry {
300300
}
301301
}
302302

303+
const SPACES: &str =
304+
" ";
305+
303306
impl<'a> Printer<'a> {
304307
pub fn last_token(&mut self) -> Token {
305308
self.buf[self.right].token.clone()
@@ -580,10 +583,25 @@ impl<'a> Printer<'a> {
580583
debug!("print String({})", s);
581584
// assert!(len <= space);
582585
self.space -= len;
583-
while self.pending_indentation > 0 {
584-
write!(self.out, " ")?;
585-
self.pending_indentation -= 1;
586+
587+
// Write the pending indent. A more concise way of doing this would be:
588+
//
589+
// write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
590+
//
591+
// But that is significantly slower than using `SPACES`. This code is
592+
// sufficiently hot, and indents can get sufficiently large, that the
593+
// difference is significant on some workloads.
594+
let spaces_len = SPACES.len() as isize;
595+
while self.pending_indentation >= spaces_len {
596+
debug_assert_eq!(SPACES.len() as isize, spaces_len);
597+
write!(self.out, "{}", SPACES)?;
598+
self.pending_indentation -= spaces_len;
586599
}
600+
if self.pending_indentation > 0 {
601+
write!(self.out, "{}", &SPACES[0..self.pending_indentation as usize])?;
602+
self.pending_indentation = 0;
603+
}
604+
587605
write!(self.out, "{}", s)
588606
}
589607

0 commit comments

Comments
 (0)