Lesson · Performance & Profiling
Performance Fundamentals
75 min readPerformance Fundamentals
Performance work starts with measurement and a correct complexity model. Optimizing the wrong code or trading clarity for microseconds without evidence usually makes software worse.
Learning goals
- Say what a performance change must show before it is worth making: a measurement of the real workload and a metric the change is expected to move.
- Estimate a loop's growth from its structure, for example one pass over the data versus a nested loop that compares every pair.
- Explain why
target in number_setanswers in expected constant time whiletarget in numbersscans references one by one. - Choose between a list and a set for repeated membership tests and justify the choice with build cost and lookup growth.
- Read a microbenchmark and name one reason its ranking might not hold for the real workload.
Mental model
Read the diagram as a decision order rather than a menu: the measurement decides which branch applies. A difference in how many operations run compounds as the input grows, while a difference in the cost of one operation is a fixed tax per step. When a collection is searched over and over, the cheapest lever is usually the change between a list scan and a set or dict lookup.
Mental model
read it top to bottom
measure the real workload ↓ what dominates: growth with input size, or cost per operation? ├─ growth: change the algorithm or the data structure (linear scan to hash lookup) └─ cost per operation: cut Python-level overhead and allocations
Core idea
Performance work is a loop: measure, form a hypothesis about the dominant cost, change one thing, and verify with the same measurement. The hypothesis answers two questions, how many operations the code runs as the input grows and what each operation costs, and the answers decide which branch of the mental model to take. The worked example answers the second question with a data structure change, replacing a scan of 100,000 references with one hash lookup.
Measure before optimizing
Optimization starts with a measured bottleneck and a target metric. A change that does not improve the real workload is not an optimization, even if a microbenchmark looks faster.
Algorithmic complexity
Complexity describes how resource use grows with input size. In Python, it often matters more than interpreter-level micro-optimizations once data becomes large.
Python-level overhead
Python-level overhead is the cost the interpreter pays for each operation on top of the computation itself: a loop iteration, a name lookup, a function call, and the dispatch of a single operator all add time. It is a constant factor per operation, so it dominates small inputs and matters less once the operation count set by the algorithm grows with the data.
Allocation cost
Creating many temporary objects adds allocator, reference-count, and garbage-collection work. Reduce allocations only after profiling shows they matter.
Data-structure choice
Data-structure choice sets the cost of the operation you perform most: membership in a list scans references one by one, while membership in a set or dict keyed by the same values is an expected constant-time hash lookup. The trade is explicit, since building the set pays one pass over the data and stores only unique keys without order, so the workload's dominant operation should pick the structure.
Walkthrough
contains_list(numbers, 99_999)runstarget in valuesagainst a list, which compares elements from index 0 upward; the target is the last element, so this one test scans all 100,000 references before it printsTrue.contains_set(number_set, 99_999)runs the sameinoperator against a set, where hashing the integer selects a slot directly, so the lookup cost no longer grows with how many numbers the set holds.set(numbers)is the one-off cost that buys those lookups: it walks the list once, hashes every integer, and stores the results, so the build pays roughly one pass over 100,000 values before the first lookup runs.- Predict before running: how the gap between the two calls changes when
numbersholds ten elements instead of 100,000, and what the set version is doing before either lookup happens.
Experiments to try
- Time both functions on 10, 1,000, and 100,000 elements and record a three-row table; state which row makes the difference obvious.
- Build the set once, run 1,000 lookups against it, then move
set(numbers)inside the lookup loop and find the repetition count where the rebuild stops being worth it. - Run both functions with a target that is not in the collection and compare the miss timings with the hit timings, explaining the list version's result.
- Replace the set with a dict whose keys are the numbers and repeat the lookups; confirm the behavior matches and note what each structure costs in memory.
Common mistakes
- Optimizing from intuition: if no measurement names the slow part, the rewrite is a guess, and it usually moves cost from one line to another rather than removing it.
- Judging versions on tiny inputs: with a handful of elements, per-operation interpreter overhead can make the slower algorithm win, and the ranking flips once the input grows.
- Rebuilding the set or dict inside the loop that uses it: membership becomes constant time, but every iteration now pays the full construction pass, which erases the gain.
- Changing a data structure without checking its other operations: a set speeds up membership but drops ordering and indexing, so code that later sorts or subscripts it pays those costs back.
Practice: Easy
- Add a comparison counter to
contains_listand print how many elements it examines for a hit on 99,999 and for a miss. Check the numbers against the target's position in the list. - Time both functions on 10, 1,000, and 100,000 elements and record a three-row table. State which row makes the difference between them obvious, and why.
- Run the example with
numbers = list(range(10))instead of 100,000 elements; note which function is still faster and connect the result to per-operation overhead on small inputs.
Practice: Medium
- Extend the example into
first_duplicate(values), once with a nested loop and once with aseenset. Time both on a 100,000-element list whose duplicate pair sits at the end, and explain the gap with operation counts rather than milliseconds. - Write
has_common(first, second)twice: once scanningfirstwithininside a loop oversecond, and once convertingfirstto a set before the loop. Time both on two 1,000-element lists whose only shared value is last. - Time the two ways to grow a list,
result = result + [item]in a loop versusresult.append(item), and explain the difference with the allocation cost of rebuilding the list each iteration.
Practice: Hard
- Write an investigation plan for one slow function from a project of yours: the measurement that would confirm it is worth optimizing, the growth analysis of its current algorithm, and the data structure or algorithm you would try first. Change no code until the plan names the evidence you are waiting for.
- Build a prediction lab with three candidates over the same data: a nested loop over 1,000 items, a single loop over 1,000,000 items with a set lookup inside, and a single loop over 1,000 items with a list scan. Write a predicted ranking, then time them and explain every surprise with growth and per-operation cost.
- Extend the worked example into a benchmark that reports, for each input size, the point where the set version starts to beat the list version; then move the set construction out of the measured block and describe how the crossover point moves.
Lesson checklist
- I can state the two questions behind any optimization: how many operations run, and what each operation costs.
- I can read a loop and predict whether its cost stays flat, grows in step with the input, or grows quadratically.
- I can explain why
target in some_setdoes not scan whiletarget in some_listdoes. - I can justify a list-versus-set choice using the dominant operation and the one-off build cost.
Remember
Performance work starts with measurement, then splits into two questions: how many operations the algorithm runs as the input grows, and what each operation costs. The worked example shows the cheapest lever for repeated lookups, building a set once so a full list scan becomes an expected constant-time hash lookup. Reach for that lever when the workload repeats the lookup, and measure at realistic sizes before trusting any ranking.
Interview angles
What is the main purpose of **Measure before optimizing**?+
Optimization starts with a measured bottleneck and a target metric. A change that does not improve the real workload is not an optimization, even if a microbenchmark looks faster.
What should you pay attention to when using **Algorithmic complexity**?+
Complexity describes how resource use grows with input size. In Python, it often matters more than interpreter-level micro-optimizations once data becomes large.
How does **Python-level overhead** fit into this lesson?+
Python-level overhead is the cost the interpreter pays per operation on top of the computation itself: each loop iteration, name lookup, function call, and operator dispatch takes real time. It is a constant factor per step, so it dominates small inputs and fades once the algorithm's operation count grows with the data.
Why can a version that wins on a 100-element list lose on a list with a million elements?+
Per-operation interpreter overhead dominates when there are few elements, so the version with the smaller constant per step can win there. Once the input grows, the number of operations set by the algorithm dominates, and the ranking can flip; judge candidates at the sizes the real workload will use.