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:
int 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?
Because you are running more often in code written in C in the interpretor. i.e. i+=1 is in Python, so slow (comparatively), whereas range(0,...) is one C call the for loop will execute mostly in C too.
Most of Python's built in method calls are run as C code. Code that has to be interpreted is much slower. In terms of memory efficiency and execution speed the difference is gigantic. The python internals have been optimized to the extreme, and it's best to take advantage of those optimizations.
It must be said that there is a lot of object creation and destruction going on with the while loop.
is the same as:
But because Python ints are immutable, it doesn't modify the existing object; rather it creates a brand new object with a new value. It's basically:
The garbage collector will also have a large amount of cleanup to do. "Object creation is expensive".
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.
range()
is implemented in C, whereasi += 1
is interpreted.Using
xrange()
could make it even faster for large numbers. Starting with Python 3.0range()
is the same as previouslyxrange()
.