rust-lang / rust-lang/rust-clippy

Detect hidden malloc in comparison of Option<String>

Open
#9,065 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.