5.4.5 · D3Scientific Computing (Python)

Worked examples — Vectorization — avoiding Python loops, speed comparison

2,028 words9 min readBack to topic

This page is a drill. The parent note built the theory: a Python loop pays a big per-element overhead , vectorized code pays a tiny , and the model is

Here we hit every case that model can throw at you — big , tiny , the exact break-even point, the trap, memory-bound reality, and a word problem.


The scenario matrix

Every problem about vectorization lives in one of these cells. The examples below are labelled with the cell (C1…C8) they cover.

Cell Case class What changes Who wins?
C1 Large (limit) , setup negligible Vectorized,
C2 Tiny (degenerate) so small dominates Loop can win
C3 Break-even the exact where times are equal Tie — solve for it
C4 / (edge) empty or single element Pure setup / almost pure setup
C5 trap np.append in a loop Neither — it's quadratic
C6 Memory-bound ceiling arithmetic is free, data movement isn't Speedup capped below
C7 Word problem real timing from a benchmark Forecast then check
C8 Exam twist np.vectorize mislabelled as fast It's a loop in disguise
Figure — Vectorization — avoiding Python loops, speed comparison

Worked examples

C1 — The large- limit


C2 — Tiny , vectorization loses


C3 — The exact break-even point

Figure — Vectorization — avoiding Python loops, speed comparison

C4 — Degenerate inputs: and


C5 — The trap (np.append in a loop)

Figure — Vectorization — avoiding Python loops, speed comparison

C6 — Memory-bound ceiling (the real-world cap)


C7 — Word problem: forecast a benchmark


C8 — Exam twist: np.vectorize is a decoy


Case-coverage checklist

Recall Did we hit every cell of the matrix?

Which example covers the large- limit? ::: C1 (). Which shows vectorization losing? ::: C2 (tiny , speedup ). Where is the exact break-even ? ::: C3 (). What happens at ? ::: C4 — loop costs , vector still pays ns setup. Which example exposes the trap? ::: C5 (np.append, copies for ). Why is real speedup below ? ::: C6 — memory-bound, ceiling . The word-problem forecast? ::: C7 — ms, . The np.vectorize decoy result? ::: C8 — , claim false.


Connections

  • Parent — the speed model these examples exercise.
  • NumPy Arrays vs Python Lists — why the append trap (C5) exists.
  • Big-O Complexity — the scaling in C5.
  • Universal Functions (ufuncs) / Numba and Cython — the real fix for C8.
  • Memory Layout and Cache — the bandwidth ceiling in C6.
  • Broadcasting Rules — vectorizing multi-dimensional cases.