Python Performance Optimization–Faster, Leaner Code

May 31, 2026 · 23 min read

Enrico Hochkoeppler

Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Python is often criticized for being slow, but the reality is more nuanced: poorly written Python is slow. Well-optimized Python — one that delegates work to C, avoids redundant computation, and chooses the right data structure — runs fast enough for the overwhelming majority of production workloads. This guide covers every major optimization category, from algorithmic improvements that change the complexity class of your code, to micro-optimizations that eliminate overhead in hot loops, to concurrency patterns that bypass the GIL altogether.

info

This article is about performance optimizations you can apply to your Python code once you start being familiar with programming in Python. If you are a beginner, or don't feel very familiar yet, we have a Python course that can help you getting started.


The Optimization Mindset: Rules Before Code​

Three principles apply to every optimization decision. Violating any of them wastes time and creates technical debt.

Profile before you optimize. Human intuition about performance is consistently wrong. The function that looks slow is rarely the bottleneck. A profiler tells you which code actually consumes time. Optimizing anything else yields negligible gains.

Fix the algorithm before fixing the code. A well-implemented O(n²) algorithm cannot be micro-optimized into an O(n log n) one. Algorithmic complexity improvements always outperform constant-factor tricks. No amount of C-level optimization can make bubble sort competitive with Timsort on a million items.

Measure, change one thing, measure again. Optimization without measurement is guesswork. Use timeit for micro-benchmarks and cProfile or scalene for full-program profiling. Run each benchmark multiple times to account for variance.

The optimization workflow is: get it right → test it → profile if slow → optimize the bottleneck → repeat.


Profiling: Finding the Real Bottleneck​

No optimization in this guide should be applied without first identifying the actual bottleneck. Python ships with a profiling toolkit sufficient for most production scenarios.

timeit — Microbenchmarking​

timeit is the correct tool for measuring the speed of small code snippets. It disables garbage collection during measurement and runs the snippet many times to produce a stable average:


import timeit



# Compare list lookup vs set lookup

list_time = timeit.timeit(

    stmt='999 in data',

    setup='data = list(range(1000))',

    number=100_000

)



set_time = timeit.timeit(

    stmt='999 in data',

    setup='data = set(range(1000))',

    number=100_000

)



print(f"List: {list_time:.4f}s")

print(f"Set:  {set_time:.4f}s")

From the command line, use -m timeit to benchmark single statements without writing a script:


python -m timeit -s "data = list(range(10000))" "9999 in data"

python -m timeit -s "data = set(range(10000))"  "9999 in data"

cProfile — Function-Level Profiling​

cProfile is Python's built-in statistical profiler. It records how many times each function was called and how long each call took. Run it from the command line on any script:


python -m cProfile -s cumtime my_script.py

The -s cumtime flag sorts results by cumulative time, showing you which function trees consume the most total execution time. This is almost always more useful than sorting by per-call time.

For interactive inspection, capture the profile data and analyze it with pstats:


import cProfile

import pstats

import io



profiler = cProfile.Profile()

profiler.enable()



# --- code under test ---

result = my_expensive_function()

# -----------------------



profiler.disable()



stream = io.StringIO()

stats = pstats.Stats(profiler, stream=stream).sort_stats('cumtime')

stats.print_stats(20)   # Print top 20 functions

print(stream.getvalue())

line_profiler — Line-by-Line Profiling​

When cProfile narrows the problem to a specific function, line_profiler shows you the cost of each individual line within it. Install it with pip install line-profiler, then decorate the function of interest:


@profile   # Added by line_profiler at runtime — don't import it

def process_records(records):

    results = []

    for record in records:

        value = record['amount'] * record['rate']

        results.append(value)

    return results

Run with:


kernprof -l -v my_script.py

The output shows execution time and hit count per line, making it straightforward to identify which specific line inside a loop is responsible for the slowdown.

scalene — CPU and Memory Profiling Together​

scalene is a modern, high-precision profiler that measures both CPU time and memory usage simultaneously. Crucially, it distinguishes between time spent in Python and time spent in native C libraries — which matters when tuning NumPy-heavy code:


pip install scalene

scalene my_script.py

scalene also separates GPU time when applicable and provides a browser-based visual report, making it the preferred tool for profiling data science and machine learning pipelines.

tracemalloc — Memory Profiling​

For memory issues, tracemalloc traces every allocation and tells you which line of code is responsible:


import tracemalloc



tracemalloc.start()



# --- code under test ---

data = [i ** 2 for i in range(1_000_000)]

# -----------------------



snapshot = tracemalloc.take_snapshot()

top_stats = snapshot.statistics('lineno')



for stat in top_stats[:5]:

    print(stat)

Visualizing cProfile Results with snakeviz​

For large profiles, reading raw text output is tedious. snakeviz renders cProfile data as an interactive flame graph in the browser:


pip install snakeviz

python -m cProfile -o profile.prof my_script.py

snakeviz profile.prof

Choosing the Right Data Structure​

The single most impactful optimization category. A wrong data structure choice can produce an O(n²) algorithm where O(1) was available.

Use set for Membership Testing​

Checking membership in a list scans every element sequentially — O(n). A set uses a hash table and performs lookups in O(1) constant time, regardless of size:


# O(n) — scans up to 1,000,000 elements

valid_ids = [i for i in range(1_000_000)]

if 999_999 in valid_ids:

    pass



# O(1) — hashes the value and jumps directly

valid_ids = set(range(1_000_000))

if 999_999 in valid_ids:

    pass

Benchmark result: set lookup is typically 750× faster than list lookup at 1,000,000 elements. The performance gap grows linearly with list size.

Sets also support efficient bulk operations — union (|), intersection (&), and difference (-) — all significantly faster than equivalent list comparisons.

Use collections.deque for Queues​

Python lists are backed by dynamic arrays. Appending to the end is O(1) amortized. Inserting or removing from the front requires shifting all remaining elements in memory — O(n):


# O(n) — shifts all elements left on every pop(0)

queue = list(range(10_000))

queue.pop(0)

queue.insert(0, -1)



# O(1) — doubly linked list, instant at both ends

from collections import deque

queue = deque(range(10_000))

queue.popleft()

queue.appendleft(-1)

Use deque whenever you need to add or remove elements from both ends. Use a list when you only append to and index into the end.

Use dict and defaultdict for Counting and Grouping​

For counting word frequencies or grouping elements, initializing a dictionary element requires a check that can be eliminated with collections.defaultdict or Counter:


# Explicit check — two dictionary lookups per word

word_counts = {}

for word in words:

    if word not in word_counts:

        word_counts[word] = 0

    word_counts[word] += 1



# defaultdict — one lookup per word

from collections import defaultdict

word_counts = defaultdict(int)

for word in words:

    word_counts[word] += 1



# Counter — C-optimized, fastest for counting

from collections import Counter

word_counts = Counter(words)

Counter(words) is the fastest of the three because the inner loop runs in C.

Prefer Tuples over Lists for Fixed Data​

Tuples are immutable. They occupy less memory than lists of the same size, are faster to create, and can be used as dictionary keys. When your data will not change after creation, use a tuple:


# List — mutable, larger memory footprint

point = [1.0, 2.0, 3.0]



# Tuple — immutable, more compact, faster to instantiate

point = (1.0, 2.0, 3.0)

Python also caches small tuples (one and two elements) in the interpreter, eliminating allocation overhead entirely for those cases.

Use the array Module for Large Numeric Sequences​

Python lists store pointers to Python objects. Each int in a list of integers is a full Python object consuming 28 bytes. The array module stores values as compact C types:


import array



# Each float uses 8 bytes (C double), not 28+ bytes (Python float object)

numbers = array.array('d', [1.0, 2.0, 3.14, 2.718])

Type codes include 'i' (signed int), 'd' (double), 'f' (float), and 'b' (signed char). Use array when you have millions of simple numeric values and do not need NumPy's mathematical operations.


Loop Optimization​

Loops are where CPython spends most of its execution time. The core strategy is to move as much computation as possible from Python bytecode into C.

List Comprehensions over for Loops​

List comprehensions execute their loop at the C level. The equivalent for loop with .append() incurs both a method lookup and a Python function call on every iteration:


# for loop — append() looked up and called in Python on every iteration

squares = []

for i in range(10_000):

    squares.append(i * i)



# List comprehension — loop and append happen in C

squares = [i * i for i in range(10_000)]

List comprehensions are consistently 20–40% faster than equivalent for loops with .append() in CPython.

Avoid Attribute Lookup Inside Loops​

In Python, every obj.method access triggers a dictionary lookup on the object and its class hierarchy at runtime. In a loop running millions of iterations, this overhead accumulates:


# method lookup triggered on every iteration — slow

result = []

for item in huge_list:

    result.append(item.upper())



# Cache the method reference before entering the loop — fast

upper = str.upper

append = result.append

result = []

for item in huge_list:

    append(upper(item))

On a 100,000-word list, eliminating dot lookups reduces execution time by approximately 30% in CPython.

Use Local Variables in Hot Functions​

CPython resolves local variable names with a direct index into the frame's local array — a single C array lookup. Global variable resolution requires a dictionary lookup at both the local and global namespace levels. Inside a tight loop, wrapping code in a function and using local variables provides a measurable speedup:


# Global scope — global variable lookup on every iteration

MULTIPLIER = 2.5

result = [x * MULTIPLIER for x in data]



# Local scope — resolved via fast LOAD_FAST opcode

def process(data):

    multiplier = 2.5   # local copy

    return [x * multiplier for x in data]

This technique also applies to frequently called methods: assign len, range, append, or any frequently accessed built-in to a local variable inside performance-critical functions.

Use Built-in Functions and itertools​

Built-in functions (sum, max, min, any, all, map, filter, zip) are implemented in C. Replacing a Python loop with a built-in call moves the iteration into the interpreter's C core:


# Python loop — slow

total = 0

for x in numbers:

    total += x



# Built-in — C loop

total = sum(numbers)

The itertools module provides C-optimized combinatorial and iteration tools. itertools.chain.from_iterable() flattens nested iterables faster than a nested Python loop:


import itertools



nested = [[1, 2], [3, 4], [5, 6]]



# Nested Python loop — slow

flat = []

for sublist in nested:

    for item in sublist:

        flat.append(item)



# itertools — C-level iteration

flat = list(itertools.chain.from_iterable(nested))

Avoid Exception Handling as Control Flow in Hot Loops​

Raising and catching exceptions involves stack unwinding and context switching. In a tight loop executing millions of times, using exceptions to handle expected conditions — rather than true errors — degrades performance:


# Exception as control flow — costly in hot loops

data = {'a': 1, 'b': 2}

for key in keys_to_lookup:

    try:

        value = data[key]

    except KeyError:

        value = 0



# Conditional check — much faster

for key in keys_to_lookup:

    value = data.get(key, 0)

Reserve try/except for genuinely exceptional conditions — file system failures, network timeouts, malformed input from external sources.

Pre-allocate Lists When Size Is Known​

When you know the final size of a list in advance, pre-allocating it avoids the repeated memory resizing Python performs when lists grow dynamically:


n = 1_000_000



# Dynamic growth — Python resizes the list multiple times

result = []

for i in range(n):

    result.append(i * 2)



# Pre-allocated — one allocation, in-place assignment

result = [0] * n

for i in range(n):

    result[i] = i * 2

Pre-allocation is approximately 25% faster than dynamic append for large lists. The gain comes from eliminating repeated calls to realloc.


String Optimization​

Use str.join() for Concatenation​

Strings are immutable. Every string + string operation creates a new string object, copies both inputs into it, and discards the old ones. In a loop, this produces O(n²) allocations and copies:


# O(n²) — creates a new string object on every iteration

sentence = ""

for word in words:

    sentence += word + " "



# O(n) — calculates total size, allocates once, fills once

sentence = " ".join(words)

str.join() is the correct and idiomatic approach for any string assembly that involves more than two components.

Use f-strings for String Formatting​

f-strings (Python 3.6+) are the fastest string formatting mechanism in CPython. They are parsed at compile time and evaluated at runtime with less overhead than % formatting or .format():


name = "Alice"

value = 42



# Slowest — runtime method lookup and argument parsing

msg = "Name: %s, Value: %d" % (name, value)



# Slower — .format() parsed at runtime

msg = "Name: {}, Value: {}".format(name, value)



# Fastest — evaluated directly at the call site

msg = f"Name: {name}, Value: {value}"

Cache str.upper and Similar Methods Outside Loops​

String method lookup inside a loop is a repeated dictionary traversal. When transforming a large list of strings with the same method, cache the unbound method before the loop:


# Method lookup on every iteration

result = [word.upper() for word in words]



# Cached unbound method — no per-iteration lookup

upper = str.upper

result = [upper(word) for word in words]

Memory Optimization​

Reducing memory consumption frequently improves speed as a side effect, because smaller working sets fit better in CPU cache and generate less garbage collection pressure.

Generators over Lists for Large Sequences​

A list comprehension computes all values immediately and stores the entire result in RAM. A generator expression uses yield semantics — it produces one value on demand and holds only the current element in memory:


# List — allocates all 1,000,000 integers immediately (~35 MB)

squares = [i ** 2 for i in range(1_000_000)]



# Generator — holds only one integer at a time (~200 bytes)

squares = (i ** 2 for i in range(1_000_000))

The generator form is O(1) memory regardless of input size. Use generators for data pipelines where you do not need random access by index and do not need to iterate the sequence more than once.

Generator functions with yield follow the same pattern for more complex cases:


def read_records(filepath):

    with open(filepath, encoding='utf-8') as f:

        for line in f:

            yield line.strip().split(',')



for record in read_records('large_dataset.csv'):

    process(record)

This streams a file of any size through your program without loading it into memory.

__slots__ for Memory-Efficient Classes​

By default, each Python object stores its attributes in a __dict__ — a dictionary attached to the instance. This provides flexibility but carries significant per-instance memory overhead. Defining __slots__ replaces __dict__ with a fixed C array of attribute slots:


# Default — each instance has a __dict__ (~232 bytes per instance)

class Point:

    def __init__(self, x, y):

        self.x = x

        self.y = y



# With __slots__ — fixed array (~56 bytes per instance)

class Point:

    __slots__ = ('x', 'y')

    def __init__(self, x, y):

        self.x = x

        self.y = y

Memory reduction is approximately 40–50% per instance. When creating millions of instances of a class — coordinates, events, records — __slots__ makes a material difference in both RAM usage and garbage collection performance.

The trade-off is that __slots__ classes cannot have new attributes added dynamically after instantiation. This is acceptable for data-holder classes with a stable attribute set.

Avoid Unnecessary Object Copies​

Passing a list to a function and modifying it in place avoids the allocation and population cost of a copy. Use in-place methods when the caller's copy does not need to be preserved:


# Creates a new list — allocation + copy

def process(data):

    new_data = data.copy()

    new_data.sort()

    return new_data



# Sorts in place — no allocation

def process(data):

    data.sort()

    return data

When you do need a copy — for example, to preserve the original for later use — be deliberate about it and avoid copying inside loops.


Import Statement Optimization​

Place Imports at Module Level​

Every import statement incurs overhead: Python checks sys.modules, potentially loads and executes the module file, and binds the name. Placing import statements inside functions means this cost is paid on every function call, not once at startup:


# Slow — import executed on every function call

def convert(text):

    import re

    return re.sub(r'\s+', ' ', text)



# Fast — import executed once when the module loads

import re



def convert(text):

    return re.sub(r'\s+', ' ', text)

Lazy Imports for Optional or Heavy Dependencies​

The exception to the module-level rule is when a dependency is rarely used, very heavy to import, or optional. In those cases, defer the import to the first actual use:


_numpy = None



def compute_matrix():

    global _numpy

    if _numpy is None:

        import numpy as _numpy

    return _numpy.zeros((1000, 1000))

This pattern avoids the startup cost of importing a large library when the function that needs it may never be called. It is particularly useful in CLI tools and plugins where most code paths do not require every dependency.


Caching and Memoization​

functools.lru_cache for Expensive Pure Functions​

When a function is pure (its output depends only on its inputs, with no side effects) and is called repeatedly with the same arguments, caching the result eliminates redundant computation:


from functools import lru_cache



@lru_cache(maxsize=128)

def fibonacci(n):

    if n < 2:

        return n

    return fibonacci(n - 1) + fibonacci(n - 2)

Without memoization, fibonacci(35) makes over 29 million recursive calls. With lru_cache, it makes 35 — one per unique value of n. The complexity changes from O(2ⁿ) to O(n).

maxsize=None creates an unbounded cache (equivalent to @functools.cache in Python 3.9+). Use bounded caches when the input domain is large or infinite, to prevent unbounded memory growth.

lru_cache is thread-safe and works correctly with multiple threads calling the same cached function concurrently.

functools.cache — Simpler Unbounded Cache (Python 3.9+)​


from functools import cache



@cache

def get_config(environment: str) -> dict:

    return load_config_from_disk(environment)

Unlike lru_cache, cache has no eviction policy — all results are stored indefinitely. Use it only when the input domain is small and bounded.


Numerical and Scientific Computing​

NumPy: Vectorized Operations on Arrays​

Python lists store pointers to Python objects. NumPy arrays store raw C-type values packed contiguously in memory. This layout allows NumPy to apply SIMD (Single Instruction Multiple Data) CPU instructions, processing multiple values simultaneously in a single clock cycle:


import numpy as np



# Python loop — operates on Python objects, one at a time

a = list(range(1_000_000))

b = list(range(1_000_000))

c = [x + y for x, y in zip(a, b)]



# NumPy — operates on C arrays with SIMD instructions

a = np.arange(1_000_000)

b = np.arange(1_000_000)

c = a + b   # Vectorized: 10–100× faster

Avoid loops over NumPy arrays. The entire performance advantage disappears when you iterate over a NumPy array with a Python for loop. Vectorized operations — arithmetic on entire arrays, boolean indexing, np.where(), np.sum(), aggregation functions — are the correct patterns:


# Wrong — iterates in Python, eliminating NumPy's advantage

result = np.array([x ** 2 for x in arr])



# Correct — vectorized, runs in C

result = arr ** 2

Pandas: Avoid iterrows(), Use Vectorization​

Pandas is built on NumPy. Row-by-row iteration with iterrows() or itertuples() negates Pandas' speed advantage by converting C-level operations into Python-level ones:


import pandas as pd



df = pd.DataFrame({'price': [10.0, 20.0, 30.0], 'quantity': [2, 3, 1]})



# Wrong — Python loop over rows

df['total'] = 0.0

for idx, row in df.iterrows():

    df.at[idx, 'total'] = row['price'] * row['quantity']



# Correct — vectorized operation across entire columns

df['total'] = df['price'] * df['quantity']

Use .apply() only as a last resort — it is faster than iterrows() but still executes a Python function call per row. Vectorized column arithmetic is always the fastest option.

Use math Module Functions for Scalar Calculations​

Python's math module provides functions implemented in C that are faster and more numerically precise than equivalent pure-Python expressions:


import math



# Slower — Python's general-purpose exponentiation operator

root = x ** 0.5



# Faster — C-implemented, dedicated square root

root = math.sqrt(x)

math.sqrt() is approximately 20–25% faster than x ** 0.5 in a tight loop. Similar gains apply to math.log(), math.exp(), math.sin(), and math.floor(). Use the math module for all scalar numerical computation; use NumPy for array computation.


Concurrency and Parallelism​

Python's Global Interpreter Lock (GIL) prevents multiple native threads from executing Python bytecodes simultaneously. The correct concurrency model depends entirely on whether the bottleneck is CPU time or I/O wait.

CPU-Bound Tasks: multiprocessing​

For tasks that spend their time computing — numerical calculations, image processing, data transformation — the GIL prevents threads from running in parallel. multiprocessing spawns separate Python processes, each with its own interpreter and GIL, utilizing all available CPU cores:


from multiprocessing import Pool

import os



def compute_chunk(chunk):

    return [x ** 2 + x ** 0.5 for x in chunk]



data = list(range(1_000_000))

chunk_size = len(data) // os.cpu_count()

chunks = [data[i:i+chunk_size] for i in range(0, len(data), chunk_size)]



with Pool() as pool:

    results = pool.map(compute_chunk, chunks)



flat_results = [item for sublist in results for item in sublist]

The overhead of spawning processes and serializing data between them means multiprocessing only pays off for sufficiently large workloads. For small tasks, the inter-process communication cost exceeds the parallelism gain.

concurrent.futures.ProcessPoolExecutor provides a higher-level, more Pythonic interface to the same underlying mechanism:


from concurrent.futures import ProcessPoolExecutor



with ProcessPoolExecutor() as executor:

    results = list(executor.map(compute_chunk, chunks))

I/O-Bound Tasks: asyncio and threading​

When your program spends most of its time waiting — for network responses, database queries, disk reads — the GIL is released during the wait. Multiple threads or coroutines can overlap their waiting time efficiently:

asyncio is the preferred model for I/O-bound work in modern Python. It uses a single thread and an event loop, with coroutines that yield control back to the loop while waiting:


import asyncio

import aiohttp



async def fetch(session, url):

    async with session.get(url) as response:

        return await response.text()



async def fetch_all(urls):

    async with aiohttp.ClientSession() as session:

        tasks = [fetch(session, url) for url in urls]

        return await asyncio.gather(*tasks)



results = asyncio.run(fetch_all(urls))

asyncio with aiohttp can handle thousands of concurrent network requests in a single thread — far more efficiently than spawning a thread per request.

threading remains appropriate for integrating with blocking libraries that do not support async:


from concurrent.futures import ThreadPoolExecutor



def fetch_url(url):

    import urllib.request

    with urllib.request.urlopen(url) as response:

        return response.read()



with ThreadPoolExecutor(max_workers=20) as executor:

    results = list(executor.map(fetch_url, urls))

When to Use What​

BottleneckToolWhyCPU-bound (Python)multiprocessingBypasses GIL, uses all coresCPU-bound (NumPy/C)Threads or nothingC extensions release the GILI/O-bound (network/disk)asyncioSingle thread, maximum concurrencyI/O-bound (blocking lib)threadingGIL released during I/O waitStateless embarrassingly parallelmultiprocessing.Pool.mapSimplest parallel pattern


Compiler and JIT Optimizations​

When Python is the bottleneck and all algorithmic improvements are exhausted, compilation is the next step.

Numba — JIT Compilation with a Single Decorator​

Numba compiles Python functions to native machine code using LLVM at the first function call. The compiled version runs at near-C speed. It is most effective on numerical loops that cannot be expressed as NumPy vectorized operations:


from numba import jit

import numpy as np



@jit(nopython=True)

def compute_pi(n):

    inside = 0

    for _ in range(n):

        x = np.random.random()

        y = np.random.random()

        if x ** 2 + y ** 2 <= 1.0:

            inside += 1

    return 4 * inside / n



# First call triggers compilation — subsequent calls use native code

result = compute_pi(10_000_000)

nopython=True forces Numba to compile the entire function to machine code without falling back to Python. If Numba cannot compile a function in nopython mode, it raises an error rather than silently running slow Python code.

PyPy — Drop-In Replacement Interpreter with JIT​

PyPy is an alternative Python interpreter that compiles Python code to native machine code at runtime using a tracing JIT compiler. For pure Python workloads — loops, data structure manipulation, string processing — PyPy typically produces 4–10× speedups over CPython with zero code changes:


# Install PyPy from pypy.org, then run any script

pypy3 my_script.py

PyPy's limitations: it has incomplete support for some C extensions (though NumPy, Pandas, and many common libraries now work), and JIT warm-up time means it is less effective for short-lived scripts. It is most beneficial for long-running server processes and computational workloads.

Cython — Static Types for C-Speed​

Cython is a superset of Python that compiles to C. You can start with pure Python and progressively add static type declarations to eliminate interpreter overhead in the hottest code paths:


# my_module.pyx

def sum_squares(int n):

    cdef int i

    cdef long total = 0

    for i in range(n):

        total += i * i

    return total

Compile with a setup.py:


from setuptools import setup

from Cython.Build import cythonize



setup(ext_modules=cythonize("my_module.pyx"))

Typed Cython code runs at C speed. Untyped Cython code runs at approximately the same speed as CPython. The value comes from adding cdef type declarations to variables in hot loops.


Sorting Optimization​

Python's built-in list.sort() and sorted() use Timsort — a hybrid sort optimized for real-world data that is already partially ordered. They are implemented in C and are difficult to beat.

Use the key parameter instead of a comparison function. A key function is called once per element, while a comparison function is called O(n log n) times. The key approach is consistently faster:


import operator



records = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]



# key= — called once per element

records.sort(key=operator.itemgetter(1))



# lambda — same semantics, slightly slower due to Python function call overhead

records.sort(key=lambda r: r[1])

operator.itemgetter() and operator.attrgetter() are implemented in C and faster than equivalent lambda functions.

Sort in place when you do not need the original order. list.sort() sorts the list in place and returns None. sorted() creates a new list. When you do not need the unsorted original, list.sort() avoids one allocation.


Performance Optimization Quick Reference​

TechniqueAreaComplexity changeDifficultyset instead of list for membershipSpeedO(n) → O(1)Trivialdeque for queuesSpeedO(n) → O(1) at frontTrivialCounter for frequency countingSpeedconstant factorTrivialstr.join() for concatenationSpeed/MemoryO(n²) → O(n)Trivialf-stringsSpeedconstant factorTrivialList comprehensionsSpeedconstant factorTrivialCache method referencesSpeedconstant factorEasyLocal variables in hot functionsSpeedconstant factorEasyGeneratorsMemoryO(n) → O(1)Easylru_cache / cacheSpeedvaries (eliminates recomputation)Easy__slots__Memoryconstant factor (~50%)MediumModule-level importsSpeedconstant factorTrivialNumPy vectorizationSpeed/Memory10–100×MediummultiprocessingSpeedlinear with core countHardasyncioSpeedconcurrency for I/OHardNumba @jitSpeednear-C for numeric loopsMediumCythonSpeedC-levelHardPyPySpeed4–10× for pure PythonMedium

Tags:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Older post

How to Fix Next.js Hydration Mismatches and Prevent Theme Flash