to_string() called through a double reference
ID |
rust.performance.inefficient_to_string |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
Reports to_string() on a receiver whose declared type is a reference to a reference - &&str or &&String - so the blanket Display implementation is used instead of the direct one.
Rationale
&&str does not get the specialised str conversion. It resolves to the blanket ToString for T: Display implementation, which routes the value through the formatting machinery: a Formatter is built and the text is written through Display rather than copied straight into a new buffer. The result is identical, so nothing in the code says why one call site is slower than the next, and double references appear silently - a closure parameter in iter().filter(…) is already one.
The following code illustrates the pattern detected by this rule:
pub fn label(name: &&str) -> String {
// FLAGGED: to_string() called through a double reference
name.to_string()
}