Skip to content

Commit a42c4de

Browse files
Owen-CH-Leungjswrenn
authored andcommitted
Revise benchmark test, and optimize fold logic to avoid use of for loop
1 parent e53a6e0 commit a42c4de

File tree

2 files changed

+10
-20
lines changed

2 files changed

+10
-20
lines changed

benches/bench1.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,11 @@ fn zip_unchecked_counted_loop3(c: &mut Criterion) {
391391
}
392392

393393
fn ziplongest(c: &mut Criterion) {
394+
let v1 = black_box((0..768).collect_vec());
395+
let v2 = black_box((0..1024).collect_vec());
394396
c.bench_function("ziplongest", move |b| {
395397
b.iter(|| {
396-
let zip = (0..768).zip_longest(0..1024);
398+
let zip = v1.iter().zip_longest(v2.iter());
397399
let sum = zip.fold(0u32, |mut acc, val| {
398400
match val {
399401
EitherOrBoth::Both(x, y) => acc += x * y,

src/zip_longest.rs

+7-19
Original file line numberDiff line numberDiff line change
@@ -54,29 +54,17 @@ where
5454
}
5555

5656
#[inline]
57-
fn fold<B, F>(self, mut acc: B, mut f: F) -> B
57+
fn fold<B, F>(self, mut init: B, mut f: F) -> B
5858
where
5959
Self: Sized,
6060
F: FnMut(B, Self::Item) -> B,
6161
{
62-
let ZipLongest { mut a, mut b } = self;
63-
64-
loop {
65-
match (a.next(), b.next()) {
66-
(Some(x), Some(y)) => acc = f(acc, EitherOrBoth::Both(x, y)),
67-
(Some(x), None) => {
68-
acc = f(acc, EitherOrBoth::Left(x));
69-
// b is exhausted, so we can drain a.
70-
return a.fold(acc, |acc, x| f(acc, EitherOrBoth::Left(x)));
71-
}
72-
(None, Some(y)) => {
73-
acc = f(acc, EitherOrBoth::Right(y));
74-
// a is exhausted, so we can drain b.
75-
return b.fold(acc, |acc, y| f(acc, EitherOrBoth::Right(y)));
76-
}
77-
(None, None) => return acc, // Both iterators are exhausted.
78-
}
79-
}
62+
let ZipLongest { a, mut b } = self;
63+
init = a.fold(init, |init, a| match b.next() {
64+
Some(b) => f(init, EitherOrBoth::Both(a, b)),
65+
None => f(init, EitherOrBoth::Left(a)),
66+
});
67+
b.fold(init, |init, b| f(init, EitherOrBoth::Right(b)))
8068
}
8169
}
8270

0 commit comments

Comments
 (0)