runtime

performance lab two ways to do one job · timed

Performance Lab

Run two ways of doing the same job on the same input. The lab checks they give the same result, then times both and measures their memory.

for loop vs list comprehension

Does building a list with append in a loop cost more than a list comprehension?

Double every number in numbers.

how it works

The loop looks up result.append and calls it as a method on every item. The comprehension runs the same loop inside one specialised piece of bytecode that adds items directly, without the attribute lookup and call.

What to notice: Comprehensions are usually somewhat faster for simple transforms; the gap is per item and rarely changes how a program scales.

When the work per item is heavy (a function call, a regex), that work dominates and the two get closer. Pick the one that reads better first. · See it in Compare Approaches

how it's measured

The input is built once and isn't timed. Each version runs 7 times, taking turns, after a warm-up run. The time shown is the middle of those runs. Times come from your browser, so they vary between computers: run again before trusting a small difference.

SIZE = 100000
numbers = list(range(SIZE))
A · for loop + append
B · list comprehension

Try it runs one version and shows its answer. Run comparison times both. Each version keeps its answer in result, so the lab can check they agree.

Python Performance Lab · Runtime