rust-lang / rust-lang/rust-clippy

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

Open
#12,240 6 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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)
    }

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating Clippy's handling of write! and write_fmt calls and review the linked Rust issue and Compiler Explorer example for the performance motivation. Add coverage for the examples shown, including literal and argument-free formatting, and verify that the lint suggests write_str only when no formatting arguments are needed.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.