Python optimizations
Caching
| Optimization technique | Case | Example |
|---|
| Decorators | recursion | factorial |
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
- Method 1: Write a decorator our self
def cache(func):
memo = {} # Dictionary to store previously computed results
@functools.wraps(func)
def wrapper(*args):
if args not in memo:
memo[args] = func(*args)
return memo[args]
return wrapper
@cahe
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
- Method 2 : Use a built-in Python decorator for this kind of tasks
from functools import lru_cahe
lru_cache(maxsize=None) # maxsize=None means the cache can grow indefinitely
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
Multi-processing (Python 3.12 adds new features)
| Optimization technique | Case | Example |
|---|
| manage several processes | parallel tasks | factorial |
Vectorization
| Optimization technique | Case | Example |
|---|
| use built-in module or 3rd party ones like numpy, numba, … instead of python for loops | heavy numeric computaion | sum of n numbers |
Published : 20 November 2025
Modified : 20 November 2025