Skip to content

Commit 4a2d4b6

Browse files
committed
perf: improve write_fmt to handle simple strings
Per @dtolnay suggestion in serde-rs/serde#2697 (comment) - attempt to speed up performance in the cases of a simple string format without arguments: ```rust write!(f, "text") -> f.write_str("text") ```
1 parent a84bb95 commit 4a2d4b6

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

library/core/src/fmt/mod.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -201,14 +201,14 @@ pub trait Write {
201201
impl<W: Write + ?Sized> SpecWriteFmt for &mut W {
202202
#[inline]
203203
default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result {
204-
write(&mut self, args)
204+
if let Some(s) = args.as_str() { self.write_str(s) } else { write(&mut self, args) }
205205
}
206206
}
207207

208208
impl<W: Write> SpecWriteFmt for &mut W {
209209
#[inline]
210210
fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
211-
write(self, args)
211+
if let Some(s) = args.as_str() { self.write_str(s) } else { write(self, args) }
212212
}
213213
}
214214

@@ -1582,8 +1582,9 @@ impl<'a> Formatter<'a> {
15821582
/// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
15831583
/// ```
15841584
#[stable(feature = "rust1", since = "1.0.0")]
1585+
#[inline]
15851586
pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1586-
write(self.buf, fmt)
1587+
if let Some(s) = fmt.as_str() { self.buf.write_str(s) } else { write(self.buf, fmt) }
15871588
}
15881589

15891590
/// Flags for formatting
@@ -2272,8 +2273,9 @@ impl Write for Formatter<'_> {
22722273
self.buf.write_char(c)
22732274
}
22742275

2276+
#[inline]
22752277
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2276-
write(self.buf, args)
2278+
if let Some(s) = args.as_str() { self.buf.write_str(s) } else { write(self.buf, args) }
22772279
}
22782280
}
22792281

0 commit comments

Comments
 (0)