From d712e3f4f4b7b002f984336031a13c864bea10b8 Mon Sep 17 00:00:00 2001 From: Yuri Astrakhan Date: Mon, 12 Feb 2024 23:44:28 -0500 Subject: [PATCH] perf: improve write_fmt to handle simple strings Per @dtolnay suggestion in https://github.com/serde-rs/serde/pull/2697#issuecomment-1940376414 - attempt to speed up performance in the cases of a simple string format without arguments: ```rust write!(f, "text") -> f.write_str("text") ``` --- library/core/src/fmt/mod.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index e1b7b46a1ed2..f95ab8dd5f39 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -201,14 +201,14 @@ pub trait Write { impl SpecWriteFmt for &mut W { #[inline] default fn spec_write_fmt(mut self, args: Arguments<'_>) -> Result { - write(&mut self, args) + if let Some(s) = args.as_str() { self.write_str(s) } else { write(&mut self, args) } } } impl SpecWriteFmt for &mut W { #[inline] fn spec_write_fmt(self, args: Arguments<'_>) -> Result { - write(self, args) + if let Some(s) = args.as_str() { self.write_str(s) } else { write(self, args) } } } @@ -1582,8 +1582,9 @@ impl<'a> Formatter<'a> { /// assert_eq!(format!("{:0>8}", Foo(2)), "Foo 2"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] + #[inline] pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result { - write(self.buf, fmt) + if let Some(s) = fmt.as_str() { self.buf.write_str(s) } else { write(self.buf, fmt) } } /// Flags for formatting @@ -2272,8 +2273,9 @@ impl Write for Formatter<'_> { self.buf.write_char(c) } + #[inline] fn write_fmt(&mut self, args: Arguments<'_>) -> Result { - write(self.buf, args) + if let Some(s) = args.as_str() { self.buf.write_str(s) } else { write(self.buf, args) } } }