4 Python Performance Optimisation Tips

Mavis LohUncategorized

Python is no doubt a powerful and versatile higher-order programming language. Whether you’re developing a web application or working with machine learning, this language has got you covered as you can quickly create a program that solves your business problem. However, the codes which you come up with to solve your business problems when developing quickly may not always be optimised for python performance. Therefore, when you’re trying to shave minutes, or even seconds, from execution time, it’s good keep these 4 strategies handy at your desk!

1. Avoid Using Global Variables

Not just limited to Python, almost all languages disapprove the unplanned use of globals. This is because using fewer global variables help you manage your  scope and memory usage more efficiently. Furthermore, Python retrieves a local variable much faster than a global one. Therefore, try to limit, or if possible, avoid that global keyword as much as you can.

2. Be Lazy With Your Module Importing

This probably sounds like an oxymoron but it really helps! Back in the day when you just started out learning Python, you were probably told to import all the modules you’re using at the start of your program. Although this habit makes it easier to keep track of what dependencies your program has, the down side to this is that all your imports are loaded at the start. So, why not try a different approach? You can load the modules only when you need them as this helps to  distribute the loading time for modules more evenly, which will likely reduce spikes of memory usage.

3. Remember the Built-In Functions

Python is a power pack that comes with a lot of built-in functions. You may be able to write high-quality, efficient codes, but it’s hard to beat the underlying libraries which have been optimised and are tested rigorously. Read up on the list of the built-ins Python provides and check if you’re duplicating any of this functions in your code.

4. Algorithms and Data Structures

To make your code run faster, take two minutes before starting to write any code and evaluate the data-structure that you are going to use. Then, look at the time complexity for the basic python data-structures and use them based on the operation that is most used in your code. Additionally, keep yourself updated of the most efficient data structures and algorithms that you can use from online forums and discussion pages. Alternatively, if you want to go that extra mile, keep an inventory of the common data structures such as nodes, queues and graphs and the situations where they are most appropriately used for!