Lesson · Performance & Profiling
Common Performance Patterns
75 min readCommon Performance Patterns
Many Python optimizations are design choices rather than tricks: select the right algorithm, use built-ins, stream data, avoid copies, and cache only when invalidation and memory costs are acceptable.
Learning goals
- Pick a built-in like
sum,max, orsortedover a hand-written accumulator loop when both express the same operation. - Explain why
result += partinside a loop copies the accumulated string again and again, and rewrite the pattern with"".join. - Turn a list-building function into a generator with
yieldand say when the single-pass trade is safe. - Spot copies such as
list(source)orsource[:]that exist only out of habit, and keep them only when independent mutation is required. - Choose between a list scan and a set lookup for repeated membership tests, and state when a cache is worth its invalidation risk.
Mental model
Each line is a trade, not a rule: caching pays only when hits outnumber misses and the cache can be invalidated, and streaming pays only when the data is consumed once. Reach for a pattern because the workload matches it, not because the pattern has a name.
Mental model
read it top to bottom
hot path identified by measurement ↓ what does the code do? recompute the same result → cache it, with a way to invalidate scan a list for membership → build a set or dict once build a big result in memory → stream with a generator grow a string in a loop → collect parts and join once hand-write a loop a built-in covers → call the built-in
Core idea
Most Python performance wins are design choices: run the operation once instead of repeatedly, keep one pass of data in memory instead of all of it, let a built-in do the looping, and match the container to the dominant operation. Each choice spends something on the other side, memory for the set or the cache, single-use for the generator, and a source review for the copies you decide to keep. The choice should follow the workload you measured.
Prefer built-ins
Built-ins such as sum, max, min, sorted, and any run their loops at C level inside CPython, so they avoid per-iteration bytecode and are usually faster than the equivalent hand-written loop. They also encode intent: sum(values) says what the loop means, and a name chosen by the standard library is harder to get subtly wrong than an accumulator you maintain yourself.
Avoid repeated string concatenation
Strings are immutable, so result += part does not extend a buffer; it builds a new string holding all previous characters plus part and rebinds the name. A loop of n concatenations therefore copies roughly 1 + 2 + ... + n characters, quadratic in the number of parts. Collect the parts in a list and call "".join(parts) once, which allocates the final string a single time.
Use generators for streaming
A generator function runs to each yield and pauses there, holding only its current state, so it can feed values to a consumer one at a time without materializing a list. sum(lines_as_numbers(data)) pulls values lazily and keeps memory flat no matter how many lines arrive; the catch is that a generator is single-use, so once exhausted it yields nothing until the function is called again.
Avoid unnecessary copies
A copy costs time and memory proportional to the sequence, and forms like list(source) and source[:] are often added out of habit rather than need. If the code only iterates the data once, pass the original object; keep a copy only when you need independent mutation or when the caller must not see your changes.
Use sets/maps for membership
Testing membership in a list scans elements until it finds a match, while a set or dict uses a hash to jump to a candidate slot, expected constant time regardless of size. A set costs one pass to build and the memory for its table, so it pays off when the same values are tested repeatedly rather than once.
Cache when appropriate
A cache trades memory and invalidation risk for repeated work, so it pays off when the same inputs recur and the result is expensive to compute. The hard part is correctness: a cached value must be discarded or refreshed when the data behind it changes, and functools.lru_cache handles storage and eviction but not invalidation, which is why it suits pure functions whose result depends only on their hashable arguments.
Walkthrough
lines_as_numbersis a generator: each pull runs to the nextyield, strips one line, skips it if empty, and hands back oneint, sosumreceives values one at a time and never holds the whole converted list.sum(lines_as_numbers(data))prints 6: the empty string is dropped byif line:, so only1,2, and3are converted and added; the generator itself holds only the current line and its integer.allowed = {"read", "write", "admin"}builds a set literal, and"write" in allowedhashes the string and checks a candidate slot instead of comparing against three elements one by one, a difference that stays small here and grows with the collection.- Predict before running: what
sumreturns fordata, how the empty entry is handled, and what would change in memory use ifdatawere a huge file handle passed to the same function.
Experiments to try
- Feed
lines_as_numbersa million lines and compare the memory reported bytracemallocwith a version that builds and returns a list. - Compare
"".join(parts)with aresult += partloop for 100,000 parts; time both and connect the second one's growth to repeated copying. - Rewrite the sum as
sum(int(line) for line in data if line.strip())and compare readability and speed with the explicit generator function. - Replace
allowedwith a list of 10,000 permissions and run 10,000 membership tests against both the list and the set; record where the set version clearly wins.
Common mistakes
- Growing a string with
+=inside a loop: each concatenation copies the whole accumulated string, so the loop's cost grows with the square of the number of parts. - Converting an iterable to a list out of habit: the materialization pays memory and time for elements that may never be read.
- Choosing a set for membership but rebuilding it inside the loop: lookups become constant time, while the per-iteration construction restores the linear cost.
- Caching results without a plan for invalidation: a stale cache returns wrong answers, which costs far more than the lookups it saved.
Practice: Easy
- Pull values from
lines_as_numbers(data)one at a time withnext()and print each; then write a list-returning version and compare the two return objects withtype. - Time
"".join(str(i) for i in range(100_000))against a loop that builds the same string with+=; record both numbers. - Run
"write" in allowedagainst the set from the worked example, then against a list and a dict with the same entries; record each result and container type.
Practice: Medium
- Rewrite
lines_as_numbersso it returns a list, then as a generator; measure peak memory withtracemallocfor a million-line input and explain the gap. - Count word frequencies over a list of 100,000 words with a plain
dictloop, then withcollections.Counter; time both and name the pattern the Counter version applies. - Add
functools.lru_cacheto a recursive Fibonacci and compare call counts and time with the uncached version; note what happens when the cached function is called with a list argument.
Practice: Hard
- Take one slow function from a project and rewrite its hot path using two patterns from this lesson, measuring each change separately and keeping both numbers.
- Build a failure lab that shows, with timings, three traps: repeated string concatenation, a set rebuilt inside a loop, and a cache without invalidation. Explain the mechanism behind each result.
- Design a streaming pipeline that reads 1,000,000 numbers, filters and transforms them in one pass, and reports counts without holding the data; state where an eager conversion could sneak in and how you would detect it.
Lesson checklist
- I can name the built-in that replaces an accumulator loop and say why it is faster.
- I can rewrite repeated
+=string building with a list and a singlejoin. - I can convert a function from returning a list to yielding values and explain the memory effect.
- I can decide whether a membership test needs a set, and whether a cache needs an invalidation rule.
Remember
These patterns are the same trade seen from several angles: do the work once instead of repeatedly, keep one pass of data in memory, and let built-ins and `join` run their loops at C level. Each choice spends something on the other side, memory for the set or the cache, single-use for the generator, and a source review for every copy you decide to keep. Apply a pattern because the measured workload matches it, not because the pattern has a name.
Interview angles
What is the main purpose of **Prefer built-ins**?+
Built-ins such as sum, max, and sorted run their loops at C level, so they are usually faster than the equivalent hand-written loop, and their names state the intent directly.
What should you pay attention to when using **Avoid repeated string concatenation**?+
Strings are immutable, so result += part builds a new string containing all previous characters plus the new part, making a loop quadratic in the number of parts. Collect the parts and call "".join(parts) once instead.
How does **Use generators for streaming** fit into this lesson?+
A generator runs to each yield and pauses, holding only its current state, so values can be consumed one at a time without materializing a list. The trade is that a generator is single-use; once exhausted, it yields nothing until the function is called again.
What does `result += part` cost inside a loop, and what should replace it?+
Each += builds a new string containing all previous characters plus the new part and rebinds the name, so a loop over n parts copies a quadratic total number of characters. Collect the parts in a list and join once with "".join(parts), which allocates the final string a single time.