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?
The
..
operator doesn’t generate an array, it returns an abstractRange
type, which is basically just a struct withstart: 0
andend: max_number
written into it: https://doc.rust-lang.org/std/ops/struct.Range.htmlThis
Range
type implements theIterator
trait, which is what gets used in the for-loop. So, basically thisnext()
method implementation is called every time it loops: https://doc.rust-lang.org/src/core/iter/range.rs.html#504-512And 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.