Skip to content

Replacer impl for FnMut() -> String leads to many wasted Strings #487

Closed
@Arnavion

Description

@Arnavion

Since Replacer is impled for FnMut(&Captures) -> String, it means a closure that wants to replace the captures with various const string literals has to allocate a new String for each invocation. It would be better if String had some sort of small-string optimization, but it doesn't.

To make it worse, the returned String is only used as a &str to be push_str()ed into the result String anyway. The optimizer is not smart enough to elid the allocation either AFAICT, such as for the code in this SO answer.

It would be nice to impl it for FnMut(&Captures) -> Cow<'static, str> instead, so that such a closure could return Cow::Borrowed("some_literal"). Doing that would be backwards-incompatible as the FnMut() -> String impl would need to be removed, since they would conflict otherwise. impl<F, I> Replacer for F where F: FnMut(&Captures) -> I, I: Into<Cow<'static, str>> { } could work as a backward-compatible impl.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions