Is there a difference in performance between these loops if max_number is extremely high, like in the billions?

for i in 0..max_number {
    // do something with i
}

Or:

let mut i = 0;
while i < max_number {
    // do something with i
    i += 1;
}

The first issue I could think of is whether the for loop would have to generate the array with all the numbers before even starting, or does the compiler optimize it so there isn’t much difference?

Ephera
62M

The .. operator doesn’t generate an array, it returns an abstract Range type, which is basically just a struct with start: 0 and end: max_number written into it: https://doc.rust-lang.org/std/ops/struct.Range.html

This Range type implements the Iterator trait, which is what gets used in the for-loop. So, basically this next() method implementation is called every time it loops: https://doc.rust-lang.org/src/core/iter/range.rs.html#504-512

And well, you can probably tell that this implementation does basically the same as your while-loop.

In general, though, these two code snippets are so commonly found that it would surprise me, if the compiler didn’t optimize both of them to be as fast as possible and therefore identical.