Skip to content

Commit

Permalink
Auto merge of #59507 - nnethercote:indent-with-SPACES, r=petrochenkov
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bors committed Mar 31, 2019
2 parents e3428db + 606f315 commit eab3eb3
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions src/libsyntax/print/pp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,8 @@ impl Default for BufEntry {
}
}

const SPACES: [u8; 128] = [b' '; 128];

impl<'a> Printer<'a> {
pub fn last_token(&mut self) -> Token {
self.buf[self.right].token.clone()
Expand Down Expand Up @@ -580,10 +582,24 @@ impl<'a> Printer<'a> {
debug!("print String({})", s);
// assert!(len <= space);
self.space -= len;
while self.pending_indentation > 0 {
write!(self.out, " ")?;
self.pending_indentation -= 1;

// Write the pending indent. A more concise way of doing this would be:
//
// write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?;
//
// But that is significantly slower than using `SPACES`. This code is
// sufficiently hot, and indents can get sufficiently large, that the
// difference is significant on some workloads.
let spaces_len = SPACES.len() as isize;
while self.pending_indentation >= spaces_len {
self.out.write_all(&SPACES)?;
self.pending_indentation -= spaces_len;
}
if self.pending_indentation > 0 {
self.out.write_all(&SPACES[0..self.pending_indentation as usize])?;
self.pending_indentation = 0;
}

write!(self.out, "{}", s)
}

Expand Down

1 comment on commit eab3eb3

@therealprof
Copy link
Contributor

@therealprof therealprof commented on eab3eb3 Apr 1, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder how a simple

        if self.pending_indentation > 0 {
            self.out.write_all(&" ".repeat(self.pending_indentation).as_ref())?;
            self.pending_indentation = 0;
        }

would fare...

Please sign in to comment.