-
Notifications
You must be signed in to change notification settings - Fork 13k
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
Special-case format!("{}", string_like)
for increased performance
#52804
Comments
Is this really possible? Normally I wouldn't think so as I'd expect that even built-in macros still expand before there is any notion of types. (But it's very possible that you know more than I do!) I think that maybe instead it could simply expand to use another trait which is specialized for these types, but which cannot be specialized by types outside the standard library. (e.g. using |
It's a compiler built-in, if you want to do magic, you probably can. OTOH, it may be possible to always expand the single-argument case to |
I think this could just apply to any type, as |
But you shouldn't. We should enact some official policy about this: if you can't represent in source form, it's a really bad idea. The main/only offender I know about is I like the In fact... since Sadly I don't see a way to pass the same arguments to both One way around it could be calling Oh and you don't really want |
Why would you need that? If it's just a single argument with |
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 aString
, I want to propose adding this special case:When expanding a call of the
format
macro (and before usingformat_args!
), check if the formatting string is literally"{}"
, and, if the only other parameterx
is either of type&str
,String
, orCow<str>
, expand the macro toToString::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 toString::from("foo")
.The text was updated successfully, but these errors were encountered: