0 day streak
rust / expert
Snippet

Optimizing Custom Iterators by Overriding Internal Fold

While standard external iteration uses next(), internal iteration via the fold method often yields superior performance. By overriding fold on a custom iterator, we bypass the repeated state checks and setup overhead required by next(), allowing the compiler to optimize loop unrolling and register allocation.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
struct StepByTwo {
current: usize,
end: usize,
}
impl Iterator for StepByTwo {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.current < self.end {
let val = self.current;
self.current += 2;
Some(val)
} else {
None
}
}
fn fold<B, F>(mut self, init: B, mut f: F) -> B
where
F: FnMut(B, Self::Item) -> B,
{
let mut accum = init;
while self.current < self.end {
accum = f(accum, self.current);
self.current += 2;
}
accum
}
}
Breakdown
1
fn fold<B, F>(mut self, init: B, mut f: F) -> B
Overrides the default fold method to implement customized internal iteration.
2
while self.current < self.end {
Iterates using a fast, local while-loop instead of yielding control back to a next() caller.
3
accum = f(accum, self.current);
Directly threads the accumulator through the closure, minimizing state transitions.