Topics in this subject
NumPy 1 min read Updated 4 Aug 2026

14. Performance Optimization

result = np.empty(len(a))

Vectorize — avoid Python loops#

# ❌ Slow
result = np.empty(len(a))
for i in range(len(a)):
    result[i] = a[i] ** 2 + 3

# ✅ Fast (vectorized)
result = a ** 2 + 3

Key techniques#

Technique Benefit
Vectorization Replace loops with array ops (10–100×)
Broadcasting Combine shapes without materializing copies
Views over copies Avoid unnecessary memory allocation
Right dtype float32/int32 halves memory & speeds cache
out= parameter Reuse buffers, reduce allocations
In-place ops (a += 1) No new array

Timing code#

import timeit
%timeit np_arr * 2          # in Jupyter
timeit.timeit("x*2", setup="import numpy as np; x=np.arange(1000)", number=10000)

💡 Tip: np.vectorize is a convenience wrapper, not a speed tool — it still loops in Python. Prefer true vectorized ufuncs.

⚠️ Common Mistake: Growing an array in a loop with np.append reallocates every time (O(n²)). Preallocate with np.empty(n) and fill, or collect in a list then np.array(list).

Interview Question: How to speed up a slow NumPy loop? Vectorize the operation, leverage broadcasting, avoid np.append in loops, use the smallest safe dtype, and reuse buffers with out=.