Skip to content

Commit a12e971

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 74c3f5a commit a12e971

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

library/core/src/fmt/mod.rs

+22-4
Original file line numberDiff line numberDiff line change
@@ -201,14 +201,22 @@ 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() {
205+
self.write_str(s)
206+
} else {
207+
write(&mut self, args)
208+
}
205209
}
206210
}
207211

208212
impl<W: Write> SpecWriteFmt for &mut W {
209213
#[inline]
210214
fn spec_write_fmt(self, args: Arguments<'_>) -> Result {
211-
write(self, args)
215+
if let Some(s) = args.as_str() {
216+
self.write_str(s)
217+
} else {
218+
write(&mut self, args)
219+
}
212220
}
213221
}
214222

@@ -1582,8 +1590,13 @@ impl<'a> Formatter<'a> {
15821590
/// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2");
15831591
/// ```
15841592
#[stable(feature = "rust1", since = "1.0.0")]
1593+
#[inline]
15851594
pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result {
1586-
write(self.buf, fmt)
1595+
if let Some(s) = fmt.as_str() {
1596+
self.buf.write_str(s)
1597+
} else {
1598+
write(self.buf, fmt)
1599+
}
15871600
}
15881601

15891602
/// Flags for formatting
@@ -2272,8 +2285,13 @@ impl Write for Formatter<'_> {
22722285
self.buf.write_char(c)
22732286
}
22742287

2288+
#[inline]
22752289
fn write_fmt(&mut self, args: Arguments<'_>) -> Result {
2276-
write(self.buf, args)
2290+
if let Some(s) = args.as_str() {
2291+
self.buf.write_str(s)
2292+
} else {
2293+
write(self.buf, args)
2294+
}
22772295
}
22782296
}
22792297

0 commit comments

Comments
 (0)