Big-O in Practice: Why Your Code Got Slow

Big-O in Practice: Why Your Code Got Slow in Python: Profiling tells you where the time went. Big-O tells you why, and whether the problem will get worse.

Concept Explanation

Profiling tells you where the time went. Big-O tells you why, and whether the problem will get worse.

Big-O describes how runtime grows as input grows. It ignores constants deliberately, because at scale they stop mattering: an O(n²) algorithm with a fast inner loop still loses to an O(n) algorithm with a slow one, given enough data.

ComplexityNamen = 1,000n = 1,000,000
O(1)Constant1 step1 step
O(log n)Logarithmic1020
O(n)Linear1,0001,000,000
O(n log n)Linearithmic10,00020,000,000
O(n²)Quadratic1,000,0001,000,000,000,000

Look at the last row. Scaling an O(n²) algorithm from a thousand items to a million makes it a million times slower, not a thousand. That is why quadratic code passes every test on your sample data and dies in production.

Python's Actual Costs

Most "why is this slow" bugs come from not knowing what a built-in operation costs:

OperationListSet / DictDeque
x in cO(n)O(1)O(n)
c[i]O(1)O(1) by keyO(n)
c.append(x)O(1) amortised—O(1)
c.insert(0, x)O(n)—O(1)
c.pop()O(1)—O(1)
c.pop(0)O(n)—O(1)
del c[i]O(n)O(1)O(n)

The bolded rows are where real programs lose their time. if item in my_list inside a loop over n items is O(n²) written in a way that looks completely innocent.

The Three Rules That Cover Most Cases

  1. Nested loops over the same data multiply. Two loops over n is O(n²).
  2. Halving the search space each step is logarithmic. Binary search on a sorted list is O(log n).
  3. A loop containing an O(n) operation is O(n²). This includes in on a list, list.pop(0), string concatenation in a loop, and df.append in pandas.

String Concatenation

Strings are immutable, so result += piece builds a new string every time, copying everything so far:

# O(n^2) -- copies the accumulated string on every iteration
result = ""
for piece in pieces:
    result += piece

# O(n) -- one allocation at the end
result = "".join(pieces)

CPython has an optimisation that sometimes rescues the first form, but it only applies when the string has a single reference, and it does not apply to lists or DataFrames at all. Use join.

Amortised Analysis

list.append is "O(1) amortised": most appends are instant, but occasionally the list is full and everything gets copied to a bigger array. Averaged over many appends, the cost per operation is constant. This is why building a list with append and converting at the end is fast, while inserting at the front repeatedly is not.

Space Complexity Matters Too

An algorithm that is fast but allocates a copy of your dataset can be worse than a slower one that works in place. Generators are the main tool here: sum(x*x for x in data) uses O(1) extra memory, while sum([x*x for x in data]) builds the whole list first.


Code Example #1 (Basic)

The list-versus-set lookup, measured.

import random
import time
from bisect import bisect_left

random.seed(0)
haystack_list = list(range(200_000))
haystack_set = set(haystack_list)
needles = [random.randrange(200_000) for _ in range(2_000)]


def timed(label, fn):
    start = time.perf_counter()
    result = fn()
    elapsed = time.perf_counter() - start
    print(f"{label:<34} {elapsed * 1000:>9.2f} ms   (found {result})")
    return elapsed


# O(n) per lookup -> O(n*m) overall
t_list = timed("list membership (O(n) each)",
               lambda: sum(1 for x in needles if x in haystack_list))

# O(1) per lookup -> O(m) overall
t_set = timed("set membership  (O(1) each)",
              lambda: sum(1 for x in needles if x in haystack_set))

# O(log n) per lookup -- when you must keep sorted order
def binary_search_count():
    found = 0
    for x in needles:
        i = bisect_left(haystack_list, x)
        if i < len(haystack_list) and haystack_list[i] == x:
            found += 1
    return found

t_bisect = timed("bisect on sorted list (O(log n))", binary_search_count)

print(f"\nset is {t_list / t_set:,.0f}x faster than list membership")
print(f"bisect is {t_list / t_bisect:,.0f}x faster, and keeps the list sorted\n")

# --- The front-insertion trap ---
from collections import deque

N = 60_000
start = time.perf_counter()
lst = []
for i in range(N):
    lst.insert(0, i)               # O(n) each -> O(n^2) total
list_time = time.perf_counter() - start

start = time.perf_counter()
dq = deque()
for i in range(N):
    dq.appendleft(i)               # O(1) each -> O(n) total
deque_time = time.perf_counter() - start

print(f"list.insert(0, x)  x{N:,}: {list_time * 1000:>8.1f} ms")
print(f"deque.appendleft() x{N:,}: {deque_time * 1000:>8.1f} ms")
print(f"deque is {list_time / deque_time:,.0f}x faster for front insertion")

The ratios are the point. These are not micro-optimisations of a few percent — swapping a list for a set on a membership check routinely turns a minute into a millisecond, and it is a one-word change.

Code Example #2 (Intermediate)

Measuring growth rates directly, and fixing a quadratic algorithm.

import random
import time
from collections import Counter, defaultdict


def measure(fn, sizes):
    """Run fn at several input sizes and report how the time actually scaled."""
    results = []
    for n in sizes:
        data = [random.randrange(n * 2) for _ in range(n)]
        start = time.perf_counter()
        fn(data)
        results.append((n, time.perf_counter() - start))
    return results


def report(label, results):
    print(f"\n{label}")
    print(f"  {'n':>8} {'time (ms)':>11} {'ratio':>8}  behaviour")
    prev = None
    for n, t in results:
        if prev is None:
            print(f"  {n:>8,} {t * 1000:>11.2f} {'--':>8}")
        else:
            ratio = t / prev if prev > 0 else 0
            # Input doubled: ~2x => linear, ~4x => quadratic
            shape = ("linear" if ratio < 2.6 else
                     "n log n" if ratio < 3.2 else "QUADRATIC")
            print(f"  {n:>8,} {t * 1000:>11.2f} {ratio:>7.1f}x  {shape}")
        prev = t


random.seed(1)
SIZES = [2_000, 4_000, 8_000, 16_000]


# ---------- Problem: find duplicates ----------
def duplicates_quadratic(data):
    """O(n^2): for every item, scan everything seen so far."""
    seen, dupes = [], []
    for item in data:
        if item in seen:            # O(n) inside an O(n) loop
            dupes.append(item)
        else:
            seen.append(item)
    return dupes


def duplicates_linear(data):
    """O(n): one hash lookup per item."""
    seen, dupes = set(), []
    for item in data:
        if item in seen:            # O(1)
            dupes.append(item)
        else:
            seen.add(item)
    return dupes


report("Duplicate detection -- list of seen items", measure(duplicates_quadratic, SIZES))
report("Duplicate detection -- set of seen items", measure(duplicates_linear, SIZES))


# ---------- Problem: group records by key ----------
records = [{"user": random.randrange(500), "amount": random.random() * 100}
           for _ in range(40_000)]


def group_quadratic(records):
    """O(n*k): re-scan every record for each distinct key."""
    keys = set(r["user"] for r in records)
    return {k: [r["amount"] for r in records if r["user"] == k] for k in keys}


def group_linear(records):
    """O(n): one pass, dict of lists."""
    out = defaultdict(list)
    for r in records:
        out[r["user"]].append(r["amount"])
    return out


for label, fn in [("group: filter per key", group_quadratic),
                  ("group: single pass  ", group_linear)]:
    start = time.perf_counter()
    result = fn(records)
    print(f"\n{label} {(time.perf_counter() - start) * 1000:>8.1f} ms  "
          f"({len(result)} groups)")


# ---------- Problem: build a string ----------
pieces = [f"row-{i}," for i in range(120_000)]

start = time.perf_counter()
slow = ""
for p in pieces:
    slow += p                       # new string allocated each time
concat_time = time.perf_counter() - start

start = time.perf_counter()
fast = "".join(pieces)              # one allocation
join_time = time.perf_counter() - start

print(f"\nstring += in a loop: {concat_time * 1000:>8.1f} ms")
print(f'"".join(pieces):     {join_time * 1000:>8.1f} ms')
print(f"join is {concat_time / join_time:,.0f}x faster (same result: {slow == fast})")


# ---------- Space: generator vs list ----------
import sys

nums = range(1_000_000)
listcomp = [x * x for x in nums]
genexp = (x * x for x in nums)

print(f"\nlist comprehension holds: {sys.getsizeof(listcomp) / 1_000_000:.1f} MB")
print(f"generator expression holds: {sys.getsizeof(genexp)} bytes")
print("Same sum, O(n) vs O(1) memory -- matters when the data does not fit in RAM.")

The ratio column in report is a technique worth keeping. Double the input and time it: roughly 2× slower means linear, roughly 4× means quadratic. You do not need to analyse the code — you can measure the exponent directly, which is far more reliable than reasoning about a function you did not write.


Common Mistakes

  1. if x in my_list inside a loop: the classic accidental O(n²). Convert to a set first.
  2. list.pop(0) or list.insert(0, x) in a loop: every operation shifts the whole list. Use collections.deque.
  3. Building strings with += in a loop: quadratic copying. Use "".join().
  4. df.append() or pd.concat inside a loop: pandas copies the entire DataFrame each time. Collect rows in a list and build once.
  5. Re-filtering a list for every key: [r for r in rows if r.key == k] inside a loop over keys. One pass with a defaultdict instead.
  6. Sorting inside a loop: sorted() is O(n log n); doing it n times is O(n² log n). Sort once outside.
  7. Optimising the wrong thing: a 10× speedup on code that takes 2% of runtime buys you 1.8%. Profile first.
  8. Assuming constants never matter: for n = 20, an O(n²) algorithm with a tight loop often beats an O(n log n) one with overhead. Big-O is about growth, not small inputs.
  9. Ignoring memory: a list comprehension over ten million rows may work; over a billion it will not. Generators cost nothing to try.
  10. Recomputing inside a loop: len(data) or expensive(config) evaluated on every iteration when the result never changes.
  11. Using list.remove() or del in a loop: each is O(n), and mutating while iterating also skips elements.

Best Practices

  • Reach for a set or dict the moment you write in on a collection you will search more than once.
  • Use collections.deque for queues — appendleft and popleft are O(1).
  • Build with append and join at the end, for strings, lists, and DataFrames alike.
  • Measure the growth rate: run at n, 2n, and 4n and look at the ratios. It identifies quadratic code in seconds.
  • Do one pass and group into a defaultdict rather than filtering repeatedly.
  • Hoist invariants out of loops: anything whose value cannot change should be computed once.
  • Prefer generators when you only iterate once — O(1) memory for free.
  • Know the complexity of the built-in you are calling. Most performance bugs are a hidden O(n) inside a loop.
  • Profile before optimising, and measure after. Intuition about Python performance is unreliable in both directions.
  • Accept a worse complexity for small, fixed n — clarity wins when the data cannot grow.
  • Use bisect when you need both order and fast lookup, and heapq when you repeatedly need the smallest item.

Practice Exercises

  1. The Growth Test: Write a function containing a nested loop and time it at n = 1,000, 2,000, 4,000, and 8,000. Print the ratio between consecutive timings and confirm it lands near 4× rather than 2×.
  2. The Membership Fix: Build a 100,000-element list and time 5,000 in lookups against it, then against a set built from the same data. Report the speedup and the one line you had to change.
  3. The Quadratic Hunt: Write a function that groups 50,000 records by key using a filter-per-key approach, then rewrite it with a single-pass defaultdict. Time both and explain in a comment which of the three rules the original violated.