Hi Pythonistas!!
Today we are going to discuss a tiny performance improvement tip. Which is “using for loop instead of while loop for definite iterations”. For loops that are faster than while loops we test this with the timeit module. If you are not familiar with the timeit module click here.
Consider the example
using while loop
import timeit
def while_loop_function():
number = 0
while number < 10000:
number += 1
time_taken = timeit.timeit(while_loop_function, number=1000)
print(time_taken)
Output
0.3551353029997699
using for loop
import timeit
def for_loop_function():
for _ in range(10000):
pass
time_taken = timeit.timeit(for_loop_function, number=1000)
print(time_taken)
output
0.11816958500003238
Reason
Here in this example, both the loops are iterating 10k times but while loop takes more time because in while loop there is comparison and increment operation is takes place. But in the for loop, this is done in range function and it is written in c. That’s why it is faster than the while loop.
While coding for definite iteration use for loop instead of while loop this makes code more readable and also has very minute improvement
Hope you have learned something in this post. Please share your suggestions and topics with afsal@parseltongue.co.in