Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize performance for string literals in Display::fmt #286

Merged
merged 2 commits into from Feb 11, 2024

Conversation

nyurik
Copy link
Contributor

@nyurik nyurik commented Feb 9, 2024

Compiler is unable to generate as efficient code for write!(f, "text") as it does for f.write_str("text"). This PR checks if the #[error("text")] uses a simple string literal without the { and } characters, and without arguments, and uses write_str if so.

Fixes #285

@nyurik nyurik force-pushed the litstr branch 2 times, most recently from cb80183 to 9c712ab Compare February 9, 2024 04:15
Compiler is unable to generate as efficient code for `write!(f, "text")` as it does for `f.write_str("text")`.  This PR checks if the `#[error("text")]` uses a simple string literal without the `{` and `}` characters, and without arguments, and uses `write_str` if so.
@nyurik nyurik changed the title Optimize simple literals for Display::fmt Optimize performance for simple literals in Display::fmt Feb 9, 2024
@nyurik nyurik changed the title Optimize performance for simple literals in Display::fmt Optimize performance for string literals in Display::fmt Feb 9, 2024
Copy link
Owner

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dtolnay dtolnay merged commit 097251d into dtolnay:master Feb 11, 2024
10 checks passed
@dtolnay
Copy link
Owner

dtolnay commented Feb 11, 2024

Published in 1.0.57.

@nyurik nyurik deleted the litstr branch February 11, 2024 19:37
@nyurik
Copy link
Contributor Author

nyurik commented Feb 12, 2024

thanks for merging and releasing it so fast! Do you know if it would be possible to detect a more advanced case when the formatting string is by itself, and the only argument is a &str ?

fn fmt(...) {
  let s = "string";
  write!("{0}", s)
}

P.S. Obviously all these things should be eventually done in the compiler... 🤞

@dtolnay
Copy link
Owner

dtolnay commented Feb 12, 2024

I do not know of a way to optimize that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Optimize performance by using write_str instead of write! when there are no formatting arguments
2 participants