Skip to content

Special-case format!("{}", string_like) for increased performance #52804

Open
@killercup

Description

@killercup

Changes like #52767 and existence of the useless_format clippy lint show that people end up writing format!("{}", a_string) way more often than they should (i.e., >0 times).

Since format is a proc macro/builtin in the compiler, and since this specific case should not have any side effects other than producing a String, I want to propose adding this special case:

When expanding a call of the format macro (and before using format_args!), check if the formatting string is literally "{}", and, if the only other parameter x is either of type &str, String, or Cow<str>, expand the macro to ToString::to_string(x).

This is quite a conservative and concrete refinement. It could easily be adjusted to support more string-like types.

And additional special case to consider is format!("foo") (with only a literal formatting string). It should expand to String::from("foo").

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: An issue proposing an enhancement or a PR with one.I-slowIssue: Problems and improvements with respect to performance of generated code.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions