Speed of For Loop vs For Item Loop

Viewed 49

I participate in coding competitions and am curious about the comparative speeds of different loops - specifically, the for loop (for i in range(...) versus the for item loop (for item in myArray).

To test this, I wrote the code below:

import time

def ForLoop():
    for i in range(len(array)):
        item = array[i]

def ForItemLoop():
    for item in array:
        a = item

array = [i for i in range(100000)]

t0 = time.monotonic_ns()
ForLoop()
t1 = time.monotonic_ns()
print("For loop time: (nanoseconds) " + str(t1-t0))
t0 = time.monotonic_ns()
ForItemLoop()
t1 = time.monotonic_ns()
print("For item loop time (nanoseconds) " + str(t1-t0))

(I wrote the a = item in ForItemLoop() because writing pass might mess things up)

The output (on Jupyter Notebook) was:

For loop time: (nanoseconds) 22432125
For item loop time (nanoseconds) 3757917

Why is the for item loop so much faster? The a = item part seems to make it super redundant, yet it still is 5 times faster?

0 Answers
Related