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

Use write_str instead of write! or write_fmt when format has no args #12240

Open
nyurik opened this issue Feb 7, 2024 · 0 comments
Open

Use write_str instead of write! or write_fmt when format has no args #12240

nyurik opened this issue Feb 7, 2024 · 0 comments
Labels
A-lint Area: New lints

Comments

@nyurik
Copy link
Contributor

nyurik commented Feb 7, 2024

What it does

Despite amazing efforts by @m-ou-se, it seems the generated assembly code for write!(f, "something") is still far more complex (and likely slower) than f.write_str("something"). While eventually I do hope it will get solved, I think Clippy can already help users to improve their code performance by suggesting to switch to write_str where possible.

Advantage

  • faster code
  • smaller compiled code

Drawbacks

  • in some cases may break consistency of only using write!
  • some day may become irrelevant (hopefully soon, but I wont bet on it)

Example

use std::fmt;

pub struct Obj(String);

impl fmt::Display for Obj {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "AAAAAAAAAAAAAAAAAAAAAA")?;
        write!(f, "{}", self.0)?;
        let s: &str = &self.0;
        write!(f, "{s}")
    }
}

Could be written as:

    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("AAAAAAAAAAAAAAAAAAAAAA")?;
        f.write_str(&self.0)?;
        let s: &str = &self.0;
        f.write_str(s)
    }
@nyurik nyurik added the A-lint Area: New lints label Feb 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

No branches or pull requests

1 participant