Profiling, Caching, and Algorithmic Speedups
Difficulty: Hard | Companies: Google, Meta, Amazon, Netflix, Stripe
"Make it faster" is an incomplete request. Interviewers are testing whether you can find the expensive line, name why it is expensive, and prove afterwards that the change helped rather than merely feeling cleverer.
Prerequisites
- !Big-O notation for common algorithms
- !Functions, decorators, and comprehensions
- !Basic familiarity with the standard library
What You'll Learn
- 1Profile CPU and memory usage before changing code
- 2Trade algorithmic complexity for constant-factor tricks
- 3Design a cache together with its invalidation policy
- 4Pick the concurrency model that matches the workload
Measure first, then argue
Every optimization starts with a measurement, because intuition about hot spots is reliably wrong in Python. A loop you rewrote by hand may be a rounding error next to a single accidental quadratic lookup, and the only way to know is to look at where the time actually goes. The discipline has three steps: establish a baseline on realistic input, change one thing, and re-measure with the same input and the same machine state.
Timing alone is not enough, but it is the cheapest signal you have. Use time.perf_counter() rather than time.time(), which can jump when the system clock is adjusted, and run enough iterations that the noise floor sits well below the effect you are trying to see. For anything more involved, cProfile shows cumulative and per-call cost, tracemalloc attributes allocations to the line that made them, and python -X importtime explains why your service takes four seconds to boot.
import cProfile
import pstats
import time
from functools import wraps
def stopwatch(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__}: {time.perf_counter() - start:.4f}s")
return result
return wrapper
def build_report(rows):
"""Deliberately naive: repeated membership scans make this quadratic."""
seen, out = [], []
for row in rows:
if row["id"] not in seen: # list scan on every iteration
seen.append(row["id"])
out.append(row)
return out
@stopwatch
def run_baseline(n=40_000):
rows = [{"id": i % (n // 2), "v": i} for i in range(n)]
return build_report(rows)
if __name__ == "__main__":
run_baseline()
cProfile.run("run_baseline()", sort="cumulative")
Reading the report, one line dominates: the in check against a list. That single observation dictates the fix. A set turns the membership test from linear into constant, and no amount of inlining, pre-binding local variables, or swapping append for a comprehension would have produced anything close to that gain.
Algorithmic wins dwarf constant factors
The honest hierarchy of performance work is: do less work, then do it with fewer allocations, then do it with faster primitives. Rewriting x * x as x ** 2 or hoisting an attribute lookup out of a loop belongs to the last tier and is only worth discussing once the first two are exhausted.
| Operation | Typical cost | Faster alternative |
|---|---|---|
| Membership test in a list | O(n) per check | set or frozenset for O(1) |
| Two nested loops for pairs | O(n²) | Sort plus two pointers, or a hash map |
| Concatenating strings in a loop | O(n²) | "".join(parts) once |
| Looking up by key while scanning | O(nĀ·m) | Build a dict index first |
| Repeated attribute or global lookup | Per access | Bind to a local inside the loop |
| Sorting on every request | O(n log n) | Sort once and maintain order |
from collections import Counter, defaultdict
def slow_pair_sum(nums, target):
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []
def fast_pair_sum(nums, target):
index = {}
for i, value in enumerate(nums):
complement = target - value
if complement in index:
return [index[complement], i]
index[value] = i
return []
def group_by_domain(emails):
groups = defaultdict(list)
for email in emails:
_, _, domain = email.rpartition("@")
groups[domain].append(email)
return dict(groups)
def word_frequencies(text):
return Counter(text.split())
Interviewers often follow up with a complexity question: if the input fits in memory, when is the hash map version worse? The answer is the constant factor and the memory ā building a dictionary of ten million entries costs allocation time and cache locality that a single sorted pass with two pointers may beat. Naming that trade-off is what separates a memorized trick from an understanding.
Caching is an invalidation problem
Memoization converts repeated work into a dictionary lookup, and Python ships a good one in functools.lru_cache. It is tempting to decorate everything expensive and move on, but a cache without a stated invalidation rule is a correctness bug waiting for the first deploy that changes an input's meaning.
from functools import lru_cache
import hashlib
import json
import time
@lru_cache(maxsize=1024)
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
def cached_with_ttl(ttl_seconds: int):
store = {}
def decorator(fn):
def wrapper(*args, **kwargs):
key = hashlib.sha256(
json.dumps([args, kwargs], sort_keys=True,
default=str).encode()).hexdigest()
hit = store.get(key)
if hit and time.time() - hit[0] < ttl_seconds:
return hit[1]
value = fn(*args, **kwargs)
store[key] = (time.time(), value)
return value
wrapper.invalidate = store.clear
return wrapper
return decorator
Three questions decide whether caching is safe. Is the function pure with respect to its arguments? Who removes entries when the underlying data changes? And what happens when every client misses at once ā do you need a jittered TTL or a single-flight guard so the backend is not thundered? Candidates who answer "I would just add Redis" without addressing those questions have not finished the design.
lru_cache has two sharp edges worth mentioning. Arguments must be hashable, so a list argument raises immediately, and the cache keeps results alive, which for a function over large objects can cost more memory than it saves. cache_clear() and cache_info() are your escape hatches when the workload shifts.
Memory: the shape of your data
CPython objects carry a header, a reference count, and a type pointer; a list of integers is a list of pointers to separate integer objects, each with its own overhead. That is why array.array('i') can hold a million integers in a fraction of the space, why __slots__ removes the per-instance dictionary, and why a generator expression allocates almost nothing compared to the list it replaces.
The practical rule is to stream anything that does not need to be sorted or indexed. for line in file reads incrementally, itertools.islice gives you chunks, and pandas-style out-of-core tools handle the cases where you genuinely need a whole dataset. Reaching for __slots__ in application code is rarely justified by memory alone, but it is a legitimate answer when you are instantiating millions of objects and the interview has already established that the allocation profile is the bottleneck.
Benchmarking honestly
A benchmark is an experiment, so it needs controls. Warm the interpreter first ā the initial run pays for bytecode compilation, module imports, and a cold CPU cache that will never appear in production. Run enough repetitions to see the spread, report the median rather than the mean, and be suspicious of a result whose variance is larger than the improvement you are claiming.
The environment matters as much as the harness. A laptop on battery with a boost clock tells you nothing about a container sharing a core with a sidecar. Pin the interpreter version, disable turbo behaviour where you can, and run the comparison back-to-back so both versions see the same thermal state. When the two candidates are close, interleave them instead of running one after the other.
Finally, remember that micro-benchmarks optimize the wrong target more often than not. Measure the operation at the scale your users experience, including the allocation and serialization the real path performs, and check the tail rather than the average, because the p99 is what turns into a support ticket. Record the numbers, the input size, and the machine in the pull request so a later reader can reproduce the claim instead of trusting it.
Threads, processes, or asyncio
Concurrency is not free speed; it is a different way to spend waiting. The GIL means pure-Python CPU work does not parallelize across threads, while I/O releases it, so threads and asyncio overlap waiting rather than computation. Processes give true parallelism at the cost of copying state across a boundary and paying serialization on every hop.
| Workload | Best fit | Why | What you give up |
|---|---|---|---|
| Pure-Python CPU | ProcessPoolExecutor | Real parallel cores | Pickling cost, shared memory |
| Blocking I/O at modest scale | ThreadPoolExecutor | Simple, works with existing libraries | Thread overhead per connection |
| Many thousands of I/O tasks | asyncio | One thread, cooperative scheduling | Everything must be await-aware |
| NumPy-heavy numerics | Vectorized calls, then processes | native code already releases the GIL | Conversion overhead if loops remain |
| Mixed pipeline | asyncio for I/O, pool for CPU | Matches each stage to its cost | Two execution models to reason about |
The measurement that matters here is throughput under load, not a stopwatch on a single call. Benchmark with a realistic concurrency level, watch the tail latency as well as the mean, and be suspicious of any parallel version that only wins because it amortized one-time setup across a short run.
Common Mistakes
Rewriting hot code before producing a profile
Fix: Capture a cProfile or timing baseline first so the optimization targets a measured cost, not a guessed one.
Caching a function whose result depends on hidden state
Fix: Either make the inputs explicit, set a TTL with a stated invalidation owner, or do not cache.
Reaching for threads to speed up CPU-bound Python
Fix: Use a process pool for real parallelism, or move the hot loop into a vectorized native call.
Building lists for data you only ever iterate once
Fix: Yield with a generator and let itertools compose the pipeline lazily.
Best Practices
- Benchmark on realistic input sizes with perf_counter and enough repetitions
- Prefer a better data structure or algorithm before touching constant factors
- Pair every cache with an explicit invalidation and stampede policy
- Keep a perf baseline in CI so regressions surface as a failing check
- Measure tail latency as well as averages when concurrency is involved
- Document the before-and-after numbers in the pull request so review stays honest
Interview Questions
Q1: How do you find the slow part of a Python program?
Start with perf_counter on coarse sections, then cProfile with sort=cumulative for call costs, and tracemalloc when the problem is allocation rather than time.
Q2: Why is a hash map often better than a nested loop?
It trades O(n²) comparisons for an O(n) pass with O(1) lookups, though it pays in memory and loses the locality a sorted two-pointer scan has.
Q3: What must be true before you cache a function?
The result must depend only on hashable arguments, and someone must own invalidation when the underlying data changes.
Q4: Threads or asyncio for ten thousand concurrent HTTP calls?
asyncio, because thread stacks and scheduling overhead grow per connection, while one event loop can await them all cooperatively.
Q5: Why does the GIL matter for optimization?
It serializes pure-Python bytecode across threads, so CPU-bound work needs processes or native code that releases the lock.
Q6: You made it faster by 40 per cent. How do you prove it?
Same input, same machine, repeated runs with a warm-up, comparing distributions rather than a single lucky timing, ideally recorded in CI.
Key Takeaways
- Profile before optimizing and re-measure after every change
- Complexity reductions beat micro-tweaks by orders of magnitude
- A cache without an invalidation owner is a latent bug
- Memory shape ā slots, arrays, generators ā matters when volume is the constraint
- Match threads to waiting and processes to computation
- Numbers in the pull request turn a performance claim into evidence