Performance tips
A few habits, like vectorizing and choosing the right dtype, make NumPy code dramatically faster.
In this page:
Performance tips
Replace Python loops with vectorized operations and pick the smallest suitable dtype. Preallocate arrays instead of growing them, avoid needless copies, and use in-place operators like += where safe. Measure with timeit before optimizing.
Note:
Appending in a loop with np.append copies the whole array every time.
Example: Performance tips
import numpy as np
n = 5
out = np.empty(n)
for i in range(n):
out[i] = i ** 2
vec = np.arange(n) ** 2
print(out)
print(vec)
print(np.array_equal(out, vec))
a = np.ones(1000, dtype=np.float32)
print(a.nbytes, "bytes")
# Output:
# [ 0. 1. 4. 9. 16.]
# [ 0 1 4 9 16]
# True
# 4000 bytes
Related Topics
Common Mistakes
- Growing arrays inside loops
- Using float64 when float32 is enough
- Optimizing without measuring
Chapter Summary
- Vectorize instead of looping
- Preallocate arrays
- Choose compact dtypes
- Measure first
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: