Consume iterator multiple times


I have an iterator and have to consume it multiple times, let’s say for example I want the sum, the max and the product of some numbers.
What’s the idiomatic way of doing so?
Assuming it’s a vec I’m iterating over and in general, only knowing it’s some kind of iterator?
I first thought of creating the iterator multiple times and doing what I want to do, but i thought doing that several times must be slower than consuming it only once, with a custom fold into a tuple for my different computations. Or is this abstracted away by the compiler, yielding equal performance?


Odds are that iterating multiple times will be slower than a single pass with a fold, particularly if the fold operation is trivial (thus magnifying the cost of iteration itself). But you can measure your specific case(s) and see what the difference is.


In case you want to go the multiple-pass route, many iterators automatically implement Clone, so you might get away with creating it once and using a clone for each operation except the last.


Iterators are already hard enough to optimize away, so it’s probably a good idea to make the compiler’s job as easy as possible. But the easiest way to check if the iterators are being “abstracted away by the compiler” is to check the assembly, which you can do either on your own computer or on