introduce

Today, we will discuss optimization techniques in Python. In this article, you’ll learn how to speed up your code by avoiding recalculation in lists and dictionaries.

Let’s first write a decorator function to calculate the execution time of the function, which is convenient to test the speed of different code:

Avoid reevaluating in lists

Within the loop

Code:

In the above function. Append recalculates the function reference each time through the loop. Total time taken by the above function after execution:

Outside the loop

Code:

In the above function, we evaluate nums.append outside the loop and use append as a variable inside the loop. Total time:

As you can see, when we append to a local variable outside the for loop, this takes much less time and can speed up the code by 201 ms.

Avoid reevaluating in the dictionary

Inside the loop

Code:

Total time taken by the above function:

Python is an evolving and popular language that is constantly being updated. In the study, it is suggested to find some study partners to study and discuss together, the effect is better. If you want to learn Python, welcome to join the Python Learning Exchange Group (627012464) to urge and learn together. There are development tools, lots of dry goods and technical information sharing!

Outside the loop

Code:

Total time taken by the above function:

As you can see, our code here is 211 milliseconds faster.