To significantly improve Python script performance, focus on bottleneck identification and algorithmic optimizations. Below are key strategies with examples:
1. Profiling & Bottleneck Identification
Use tools like cProfile or line_profiler to pinpoint slow code sections[3][5][7]. Example: Basic profiling
python
import cProfile
def my_function():
# Code to profile
cProfile.run('my_function()')
2. Caching & Avoiding Redundant Computation
Apply functools.lru_cache to memoize expensive function calls[1][3][5]. Example: Caching Fibonacci
python
from functools import lru_cache
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
3. Vectorization with NumPy
Replace Python loops with NumPy operations for numerical tasks[1][3][6]. Example: Matrix multiplication
python
import numpy as np
# Slow Python loop
result = []
for i in range(1000):
row = []
for j in range(1000):
row.append(i * j)
result.append(row)
# Fast NumPy
matrix = np.arange(1000 * 1000).reshape(1000, 1000)
result = matrix * matrix.T # Vectorized operation
4. String Optimization
Use list accumulation + join() instead of concatenation[2][7]. Example: Efficient string building
python
# Slow
result = ""
for item in data:
result += str(item)
# Fast
result = "".join(str(item) for item in data)
5. Short-Circuiting & Early Returns
Optimize conditionals to minimize unnecessary checks[1][2]. Example: Early exit
python
def process_data(data):
if not data:
return # Exit early
# Process data
6. Memory Optimization
Use __slots__ in classes to reduce memory overhead[4]. Example: Optimized class
python
class OptimizedClass:
__slots__ = ('x', 'y') # Restrict attributes
def __init__(self, x, y):
self.x = x
self.y = y
from itertools import islice
# Replace nested loops with itertools
data = [x for x in islice(iterable, 1000)]
8. Avoiding Global Variables
Access local variables instead of globals for faster lookups[2][4]. Example: Local variable caching
python
def loop_optimized():
func = some_object.some_method # Cache method reference
for item in my_list:
result = func(item) # Faster than repeated attribute access
9. Parallel Processing
For CPU-bound tasks, use multiprocessing to bypass GIL[3][4]. Example: Parallel computation
python
import multiprocessing
def compute(x):
return x ** 2
with multiprocessing.Pool() as pool:
results = pool.map(compute, [1, 2, 3, 4])
10. Third-Party Tools
Consider Numba (JIT compilation) or Cython for critical code[4][6]. Example: Numba JIT
python
from numba import jit
@jit(nopython=True)
def compute(x):
return x ** 2
Key Takeaway: Always profile first to target optimizations effectively. For async frameworks, focus on reducing overhead in event loops and using efficient data structures[4][7].