From a Swift perspective, your for
loop actually translates to something like this:
let range = 0..<10000000
var iterator = range.makeIterator()
while let next = iterator.next() {
...
}
Notice that's a lot of calls to next
on the range's iterator, which has its own state that has to be kept track of, and IndexingIterator.next
calls a bunch of protocol methods, dispatching which takes some time too as it has to lookup the witness table. See exactly what calls Iterator.next
is going to make here.
If you are in debug mode, none of that is going to be optimised.
Compare that to your while loop, which is basically set something to 0, compare, do the thing in the loop, add 1 to it, repeat. Clearly this is much simpler to do than calling all those methods.
If you enable optimisations however, the compiler can see that the for loop is doing what the while loop does anyway.
Because I find it interesting, I did a little time profile of a loop such as:
var s = ""
for i in 0...10000000 {
s += "(i)"
}
80% of the time is spent on next()
, and look at how many things it does! My screenshot can't even contain everything. The string concatenating only takes up about 6% (not in the screenshot).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…