Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize HashSet contains+insert usage #11103

Closed
nyurik opened this issue Jul 4, 2023 · 3 comments · Fixed by #12873
Closed

Optimize HashSet contains+insert usage #11103

nyurik opened this issue Jul 4, 2023 · 3 comments · Fixed by #12873
Assignees
Labels
A-lint Area: New lints

Comments

@nyurik
Copy link
Contributor

nyurik commented Jul 4, 2023

What it does

Optimize hashset (and possibly similar HashMap?) usage when the user first uses contains() to check the non-existence of a value, followed by insertion.

Advantage

  • Faster code
  • Shorter code

Drawbacks

No response

Example

use std::collections::HashSet;

fn main() {
    let mut vals = HashSet::new();
    insert_if(&mut vals, 10);
}

fn insert_if(set: &mut HashSet<i32>, value: i32) {
    if !set.contains(&value) {
        set.insert(value);
        println!("inserted {value:?}");
    }
}

Could be written as:

fn insert_if(set: &mut HashSet<i32>, value: i32) {
    if set.insert(value) {
        println!("inserted {value:?}");
    }
}
@nyurik nyurik added the A-lint Area: New lints label Jul 4, 2023
@lochetti
Copy link
Contributor

lochetti commented Jul 4, 2023

Interesting! I will try to do it. I might need some help, though :)
If you know some other lint that has similar logic (looking if two expressions happen one after another and then linting) let me know.

@rustbot claim

@Centri3
Copy link
Member

Centri3 commented Jul 5, 2023

I believe unnecessary_unwrap, @lochetti ^^

@Jarcho
Copy link
Contributor

Jarcho commented Jul 5, 2023

map_entry does this for HashMap/BTreeMap.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
4 participants