Skip to content

Commit b4b495e

Browse files
committed
Optimize unnecessary check in VecDeque::retain
Signed-off-by: Xuanwo <[email protected]>
1 parent 2bd17c1 commit b4b495e

File tree

2 files changed

+59
-8
lines changed

2 files changed

+59
-8
lines changed

library/alloc/src/collections/vec_deque/mod.rs

+24-8
Original file line numberDiff line numberDiff line change
@@ -2129,16 +2129,32 @@ impl<T, A: Allocator> VecDeque<T, A> {
21292129
F: FnMut(&T) -> bool,
21302130
{
21312131
let len = self.len();
2132-
let mut del = 0;
2133-
for i in 0..len {
2134-
if !f(&self[i]) {
2135-
del += 1;
2136-
} else if del > 0 {
2137-
self.swap(i - del, i);
2132+
let mut idx = 0;
2133+
let mut cur = 0;
2134+
2135+
// Stage 1: All values are retained.
2136+
while cur < len {
2137+
if !f(&self[cur]) {
2138+
cur += 1;
2139+
break;
21382140
}
2141+
cur += 1;
2142+
idx += 1;
21392143
}
2140-
if del > 0 {
2141-
self.truncate(len - del);
2144+
// Stage 2: Swap retained value into current idx.
2145+
while cur < len {
2146+
if !f(&self[cur]) {
2147+
cur += 1;
2148+
continue;
2149+
}
2150+
2151+
self.swap(idx, cur);
2152+
cur += 1;
2153+
idx += 1;
2154+
}
2155+
// Stage 3: Trancate all values after idx.
2156+
if cur != idx {
2157+
self.truncate(idx);
21422158
}
21432159
}
21442160

library/alloc/src/collections/vec_deque/tests.rs

+35
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,39 @@ fn bench_pop_back_100(b: &mut test::Bencher) {
4040
})
4141
}
4242

43+
#[bench]
44+
#[cfg_attr(miri, ignore)] // isolated Miri does not support benchmarks
45+
fn bench_retain_whole_10000(b: &mut test::Bencher) {
46+
let v = (1..100000).collect::<VecDeque<u32>>();
47+
48+
b.iter(|| {
49+
let mut v = v.clone();
50+
v.retain(|x| *x > 0)
51+
})
52+
}
53+
54+
#[bench]
55+
#[cfg_attr(miri, ignore)] // isolated Miri does not support benchmarks
56+
fn bench_retain_odd_10000(b: &mut test::Bencher) {
57+
let v = (1..100000).collect::<VecDeque<u32>>();
58+
59+
b.iter(|| {
60+
let mut v = v.clone();
61+
v.retain(|x| x & 1 == 0)
62+
})
63+
}
64+
65+
#[bench]
66+
#[cfg_attr(miri, ignore)] // isolated Miri does not support benchmarks
67+
fn bench_retain_half_10000(b: &mut test::Bencher) {
68+
let v = (1..100000).collect::<VecDeque<u32>>();
69+
70+
b.iter(|| {
71+
let mut v = v.clone();
72+
v.retain(|x| *x > 50000)
73+
})
74+
}
75+
4376
#[bench]
4477
#[cfg_attr(miri, ignore)] // isolated Miri does not support benchmarks
4578
fn bench_pop_front_100(b: &mut test::Bencher) {
@@ -54,6 +87,8 @@ fn bench_pop_front_100(b: &mut test::Bencher) {
5487
})
5588
}
5689

90+
91+
5792
#[test]
5893
fn test_swap_front_back_remove() {
5994
fn test(back: bool) {

0 commit comments

Comments
 (0)