Other Versions
pythonperformanceoptimizationprofiling
Abstraction: Practical Python performance optimization techniques and profiling tools
Key points:
- Profile before optimizing; use
cProfile(C implementation, faster thanprofile) andtimeitmodule introduced in Python 2.3 - String concatenation: use
"".join(list)instead of repeated+=; immutable strings make concatenation O(n^2) otherwise - Loop optimization:
map()and list comprehensions push loop into C; cache method references outside loops to avoid repeated attribute lookup - Generator expressions (Python 2.4+) avoid building full list in memory; use with
sum(),min(),max() xrangeoverrangein Python 2 avoids allocating all integers at once; Python 3rangeis lazy by default- Import statements inside functions add overhead when called repeatedly; lazy imports with module-level sentinel avoid redundant work
Connections: Python · Python Performance · Profiling · Optimization
Source: https://wiki.python.org/moin/PythonSpeed/PerformanceTips