Python code optimization tips for developers
- Optimize the slow code first. In the case of Python, PyPy helps you use less space and work faster than CPython’s typical bulk allows for.
- Profile codes (using CProfile or PyCallGraph, say) to analyze how they work in different situations and estimate the time taken.
- Python strings tend to be immutable and slow. Concatenate them with the .join() method rather than relying on the memory-hungry (+) operator alone.
- Use list comprehension rather than loops for faster coding and execution.
- For memory optimization, prefer xrange over the range function to speed up the creation of integer lists.
Full post here, 4 mins read