Owned copy allocated only to be borrowed again
ID |
rust.performance.unnecessary_to_owned |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
Reports a reference taken directly to a freshly allocated owned copy of a string or byte slice - &x.to_string(), &x.to_owned(), &x.to_vec(), &x.clone(), &String::from(x) - where the receiver is already a &str, String, Vec<u8> or &[u8].
Rationale
The copy is allocated, borrowed, and dropped at the end of the statement, so nothing keeps it. The borrow that comes back derefs to the same view the original already offered, which means the allocation and the byte-for-byte copy buy nothing. In a loop or a formatting helper that is one heap allocation per call on a path that could touch none.
The following code illustrates the pattern detected by this rule:
fn width(text: &str) -> usize {
text.len()
}
pub fn borrowed_slice(name: &str) -> usize {
// FLAGGED: Owned copy allocated only to be borrowed again
width(&name.to_string())
}