Skip to content

Optimize HashSet contains+insert usage #11103

Closed
@nyurik

Description

@nyurik

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:?}");
    }
}

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions