-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Suggest faster .contains()
instead of .iter().any()
for [u8]
and [i8]
slices
#13353
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
Labels
A-lint
Area: New lints
Comments
If anyone wants to try it, run this with [dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
[[bench]]
name = "my_benchmark"
harness = false // benches/my_benchmark.rs
use std::hint::black_box;
use criterion::{criterion_group, criterion_main, Criterion};
#[inline(never)]
pub fn contains(values: &[u8]) -> bool {
values.contains(&10)
}
#[inline(never)]
pub fn has_any(values: &[u8]) -> bool {
values.iter().any(|x| *x == 10)
}
fn criterion_benchmark(c: &mut Criterion) {
let data = vec![20u8; 1000];
let slice = &data[..];
c.bench_function("ref_zero", |b| b.iter(|| contains(black_box(slice))));
c.bench_function("has_any", |b| b.iter(|| has_any(black_box(slice))));
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches); |
This is from specialization for |
@Jarcho ah, thx, i missed the specialization. Thus, it makes perfect sense to do this as a lint for u8 and i8 |
.iter().any()
with .contains()
.iter().any()
with .contains()
.iter().any()
with .contains()
.contains()
instead of .iter().any()
for [u8]
and [i8]
slices
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
What it does
Suggest to replace
values.iter().any(|&x| x == 10)
withvalues.contains(&10)
as shown in the example for x beingu8
or ani8
. Contains uses specialization, thus gains 8-10x in performance.The generated assembly is significantly different too (see here).
Advantage
Drawbacks
Example
Could be written as:
The text was updated successfully, but these errors were encountered: