The other day I was doing some Python benchmarking and I came across something interesting. Below are two loops that do more or less the same thing. Loop 1 takes about twice as long as loop 2 to execute.
Loop 1:
i = 0
while i < 100000000:
i += 1
Loop 2:
for n in range(0,100000000):
pass
Why is the first loop so much slower? I know it's a trivial example but it's piqued my interest. Is there something special about the range() function that makes it more efficient than incrementing a variable the same way?
Best Answer
see the disassembly of python byte code, you may get a more concrete idea
use while loop:
The loop body has 10 op
use range:
The loop body has 3 op
The time to run C code is much shorter than intepretor and can be ignored.