How to make loops run faster using Python?

PythonProgrammingServer Side Programming

This is a language agnostic question. Loops are there in almost every language and the same principles apply everywhere. You need to realize that compilers do most heavy lifting when it comes to loop optimization, but you as a programmer also need to keep your loops optimized.

It is important to realize that everything you put in a loop gets executed for every loop iteration. They key to optimizing loops is to minimize what they do. Even operations that appear to be very fast will take a long time if the repeated many times. Executing an operation that takes 1 microsecond a million times will take 1 second to complete.

Don't execute things like len(list) inside a loop or even in its starting condition.

example

a = [i for i in range(1000000)]
length = len(a)
for i in a:
   print(i - length)

is much much faster than

a = [i for i in range(1000000)]
for i in a:
   print(i - len(a))

You can also use techniques like Loop Unrolling(https://en.wikipedia.org/wiki/Loop_unrolling) which is loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space-time tradeoff.

Using functions like map, filter, etc. instead of explicit for loops can also provide some performance improvements.

raja
Published on 19-Apr-2018 17:47:25
Advertisements