Skip to content

Commit d055c06

Browse files
Rollup merge of rust-lang#142549 - the8472:intersperse-fold-tweak, r=tgross35
small iter.intersperse.fold() optimization No need to call into fold when the first item is already None, this avoids some redundant work for empty iterators. "But it uses Fuse" one might want to protest, but Fuse is specialized and may call into the inner iterator anyway.
2 parents 46cc60b + e6c3008 commit d055c06

File tree

1 file changed

+10
-1
lines changed

1 file changed

+10
-1
lines changed

library/core/src/iter/adapters/intersperse.rs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,16 @@ where
223223
{
224224
let mut accum = init;
225225

226-
let first = if started { next_item.take() } else { iter.next() };
226+
let first = if started {
227+
next_item.take()
228+
} else {
229+
let n = iter.next();
230+
// skip invoking fold() for empty iterators
231+
if n.is_none() {
232+
return accum;
233+
}
234+
n
235+
};
227236
if let Some(x) = first {
228237
accum = f(accum, x);
229238
}

0 commit comments

Comments
 (0)