rust-lang / rust-lang/rust-clippy
Detect hidden malloc in comparison of Option<String>
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
When comparing Option<String>, we may create an intermediate object for the sole purpose of the comparison, and for that we allocate the inner String object. Instead we can compare the inner str object without allocation:
fn main() {
let string = Some("Hello, world!".to_owned());
// There is an unnecessary malloc hidden in this statement in `.to_owned()`
assert!(string == Some("Hello, world!".to_owned()));
// This comparison is done without allocation
assert!(string.as_deref() == Some("Hello, world!"));
}
Lint Name
string-allocation-during-comparison
Category
perf
Advantage
- Saves redundant memory allocation
- Faster
Drawbacks
None that I can think of
Example
assert!(string == Some("Hello, world!".to_owned()));
Could be written as:
assert!(string.as_deref() == Some("Hello, world!"));
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Search rust-clippy for the lint name string-allocation-during-comparison and inspect existing lints that analyze comparisons and suggest rewrites. Use the provided Option<String> example as the behavioral baseline; done means the allocating comparison is detected and the as_deref() form is recommended without false positives.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100