Conversation
|
r? @dswij rustbot has assigned @dswij. Use Why was this reviewer chosen?The reviewer was selected based on:
|
|
Quick benchmark: use std::collections::HashSet;
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
#[inline(never)]
fn vec_clear(x: &mut Vec<u64>) {
x.clear();
x.shrink_to_fit();
}
#[inline(never)]
fn vec_take(x: &mut Vec<u64>) {
std::mem::take(x);
}
#[inline(never)]
fn set_clear(x: &mut HashSet<u64>) {
x.clear();
x.shrink_to_fit();
}
#[inline(never)]
fn set_take(x: &mut HashSet<u64>) {
std::mem::take(x);
}
fn clear_vs_take(c: &mut Criterion) {
for size in [128, 1024, 8196] {
let mut data = vec![0u64; size];
rand::fill(&mut data[..]);
c.bench_function(&format!("vec/clear+shrink_to_fit/{size}"), |b| {
b.iter_batched(
|| data.to_vec(),
|mut v| vec_clear(&mut v),
BatchSize::SmallInput,
);
});
c.bench_function(&format!("vec/std::mem::take/{size}"), |b| {
b.iter_batched(
|| data.to_vec(),
|mut v| vec_take(&mut v),
BatchSize::SmallInput,
);
});
c.bench_function(&format!("hashset/clear+shrink_to_fit/{size}"), |b| {
b.iter_batched(
|| data.iter().copied().collect::<HashSet<_>>(),
|mut set| set_clear(&mut set),
BatchSize::SmallInput,
);
});
c.bench_function(&format!("hashset/std::mem::take/{size}"), |b| {
b.iter_batched(
|| data.iter().copied().collect::<HashSet<_>>(),
|mut set| set_take(&mut set),
BatchSize::SmallInput,
);
});
}
}
criterion_group!(benches, clear_vs_take);
criterion_main!(benches);For From the assembly (https://godbolt.org/z/TdncMhzhj):
In addition to potential performance benefits, |
|
This lint only searches for consecutive |
|
Would |
|
r? clippy |
Yeah, good catch. I could change to that if needed. |
Summary
Add
clear_then_shrink, a newclippy::perflint for consecutiveclear(); shrink_to_fit();calls on standard library containers.The lint suggests replacing the pattern with
std::mem::take(...)forVec,VecDeque,String,PathBuf,OsString,HashMap,HashSet, andBinaryHeap.Tests
Added UI tests for supported containers,
&mutreceivers, non-linted cases, and MSRV handling.changelog: new lint: [
clear_then_shrink]