Skip to content

Suggest faster .contains() instead of .iter().any() for [u8] and [i8] slices #13353

Closed
@nyurik

Description

@nyurik

What it does

Suggest to replace values.iter().any(|&x| x == 10) with values.contains(&10) as shown in the example for x being u8 or an i8. Contains uses specialization, thus gains 8-10x in performance.

The generated assembly is significantly different too (see here).

Advantage

  • 8x faster code

Drawbacks

  • none(?)

Example

#[inline(never)]
pub fn has_any(values: &[u8]) -> bool {
    values.iter().any(|&x| x == 10)
}

Could be written as:

#[inline(never)]
pub fn ref_zero(values: &[u8]) -> bool {
    values.contains(&10)
}

Metadata

Metadata

Assignees

No one assigned

    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