]> git.lizzy.rs Git - rust.git/commitdiff
Optimize indentation in the pretty printer.
authorNicholas Nethercote <nnethercote@mozilla.com>
Thu, 28 Mar 2019 21:32:13 +0000 (08:32 +1100)
committerNicholas Nethercote <nnethercote@mozilla.com>
Sun, 31 Mar 2019 20:55:25 +0000 (07:55 +1100)
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.

src/libsyntax/print/pp.rs

index d8a8cbb655b4b548720afa23594b5cef95783bc4..45eb6995a769957a84c66dbba9fa3c3634783a21 100644 (file)
@@ -300,6 +300,8 @@ fn default() -> Self {
     }
 }
 
+const SPACES: [u8; 128] = [b' '; 128];
+
 impl<'a> Printer<'a> {
     pub fn last_token(&mut self) -> Token {
         self.buf[self.right].token.clone()
@@ -580,10 +582,24 @@ pub fn print_string(&mut self, s: Cow<'static, str>, len: isize) -> io::Result<(
         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)
     }