rust-lang / rust-lang/rust-clippy

Use dereference instead of references for comparisons

Open
#10,100 4 comments 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

There are two possibilities for comparing a variable and a reference

either making a reference to the variable

&variable == reference

or dereferencing the reference

variable == *reference

Since dereferencing generates better assembly it should be recommended instead of its counterpart

Here is the assembly I get with the compiler explorer with the following source code

pub fn compare_with_reference(a: u32, b: &u32) -> bool {
    &a == b
}

pub fn compare_with_dereference(a: u32, b: &u32) -> bool {
    a == *b
}
compare_with_reference:
        sub     rsp, 24
        mov     dword ptr [rsp + 4], edi
        mov     qword ptr [rsp + 8], rsi
        lea     rax, [rsp + 4]
        mov     qword ptr [rsp + 16], rax
        lea     rdi, [rsp + 16]
        lea     rsi, [rsp + 8]
        call    qword ptr [rip + core::cmp::impls::<impl core::cmp::PartialEq<&B> for &A>::eq@GOTPCREL]
        mov     byte ptr [rsp + 3], al
        mov     al, byte ptr [rsp + 3]
        and     al, 1
        movzx   eax, al
        add     rsp, 24
        ret

compare_with_dereference:
        cmp     edi, dword ptr [rsi]
        sete    al
        and     al, 1
        movzx   eax, al
        ret
Lint Name

unnecessary_reference_in_comparison

Category

perf

Advantage
  • Unified way to compare variable with references across the code base
  • Smaller faster and more readable assembly is generated
Drawbacks
  • With opt-level 1 and higher the two ways of comparing generate the same assembly
Example
pub fn compare(a: u32, b: &u32) -> bool {
    &a == b
}

Could be written as:

pub fn compare(a: u32, b: &u32) -> bool {
    a == *b
}

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

No implementation file or test is named. Start by locating the unnecessary_reference_in_comparison lint entry points and related tests in rust-lang/rust-clippy, then review how comparison lints define applicability and diagnostics. Done means the lint consistently recommends dereferencing for the shown comparison and its tests cover the intended behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
devtools, performance
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.