Skip to content

Commit

Permalink
fmt: Skip calling write_str for empty strings
Browse files Browse the repository at this point in the history
`format_args!` uses one string literal per used `{}`, in many cases, the
separating string pieces are empty.

For example, `write!(w, "{}", x);` will attempt to write one empty
string before the `{}` format, and `write!(w, "{}{}{}", x, y, z);" will
write three empty string pieces between formats.

Simply skip writing if the string is empty. It is a cheap branch
compared to the virtual Write::write_str call that it makes possible to
skip.

It does not solve issue rust-lang#10761 in any way, yet that's where I noticed
this. The testcase in the issue shows a performance difference between
`write!(w, "abc")` and `write!(w, "{}", "abc")`, and this change halves
the size of the difference.
  • Loading branch information
bluss committed Feb 29, 2016
1 parent 0913004 commit 32235db
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/libcore/fmt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,15 +792,19 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
None => {
// We can use default formatting parameters for all arguments.
for (arg, piece) in args.args.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write_str(*piece));
if !piece.is_empty() {
try!(formatter.buf.write_str(*piece));
}
try!((arg.formatter)(arg.value, &mut formatter));
}
}
Some(fmt) => {
// Every spec has a corresponding argument that is preceded by
// a string piece.
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write_str(*piece));
if !piece.is_empty() {
try!(formatter.buf.write_str(*piece));
}
try!(formatter.run(arg));
}
}
Expand All @@ -809,7 +813,9 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write_str(*piece));
if !piece.is_empty() {
try!(formatter.buf.write_str(*piece));
}
}
None => {}
}
Expand Down

0 comments on commit 32235db

Please sign in to comment.