Skip to content

Commit eab3eb3

Browse files
committed
Auto merge of #59507 - nnethercote:indent-with-SPACES, r=petrochenkov
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.
2 parents e3428db + 606f315 commit eab3eb3

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

src/libsyntax/print/pp.rs

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

303+
const SPACES: [u8; 128] = [b' '; 128];
304+
303305
impl<'a> Printer<'a> {
304306
pub fn last_token(&mut self) -> Token {
305307
self.buf[self.right].token.clone()
@@ -580,10 +582,24 @@ impl<'a> Printer<'a> {
580582
debug!("print String({})", s);
581583
// assert!(len <= space);
582584
self.space -= len;
583-
while self.pending_indentation > 0 {
584-
write!(self.out, " ")?;
585-
self.pending_indentation -= 1;
585+
586+
// Write the pending indent. A more concise way of doing this would be:
587+
//
588+
// write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
589+
//
590+
// But that is significantly slower than using `SPACES`. This code is
591+
// sufficiently hot, and indents can get sufficiently large, that the
592+
// difference is significant on some workloads.
593+
let spaces_len = SPACES.len() as isize;
594+
while self.pending_indentation >= spaces_len {
595+
self.out.write_all(&SPACES)?;
596+
self.pending_indentation -= spaces_len;
586597
}
598+
if self.pending_indentation > 0 {
599+
self.out.write_all(&SPACES[0..self.pending_indentation as usize])?;
600+
self.pending_indentation = 0;
601+
}
602+
587603
write!(self.out, "{}", s)
588604
}
589605

0 commit comments

Comments
 (0)