Python optimizations

Caching

Optimization techniqueCaseExample
Decoratorsrecursionfactorial
  • Before optimization
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
  • After optimization
  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)

  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 techniqueCaseExample
manage several processesparallel tasksfactorial

Vectorization

Optimization techniqueCaseExample
use built-in module or 3rd party ones like numpy, numba, … instead of python for loopsheavy numeric computaionsum of n numbers
Published : 20 November 2025
Modified : 20 November 2025

© November 2025