Sub topic 16
Performance Tips and Common Pitfalls
This chapter assumes you know views versus copies, vectorized arithmetic, boolean masks, and strides from earlier chapters. It collects the habits that keep NumPy code fast and the mistakes that produce wrong results without raising an error.
Prefer vectorized expressions
A Python loop over an array runs interpreter code once per element. A vectorized expression runs one compiled loop over the whole buffer. Replace loops with ufuncs, reductions, or np.dot whenever you can.
import numpy as np
x = np.arange(1_000_000, dtype=np.float64)
total = 0.0
for v in x:
total += v * v
total_vec = np.dot(x, x)
print(np.isclose(total, total_vec)) # TrueCompare floats with np.isclose, not ==. The two sums add terms in different orders, so tiny rounding differences are normal.
Preallocate instead of growing
np.append and np.concatenate allocate a new array and copy every existing element. Calling them inside a loop makes the work grow quadratically. Allocate the output once and fill it.
import numpy as np
n = 5
out = np.empty(n, dtype=np.int64)
for i in range(n):
out[i] = i * i
print(out) # [ 0 1 4 9 16]np.empty does not initialize memory, so write every element before you read it. Use np.zeros if you are unsure.
Know which indexing returns a copy
| Indexing form | Result |
|---|---|
| Basic slice such as `a[1:4]` | View |
| Boolean mask such as `a[a > 2]` | Copy |
| Integer list such as `a[[0, 2]]` | Copy |
This matters when you chain operations. Assigning into the result of a mask changes a temporary copy, not the original.
import numpy as np
a = np.arange(6)
a[a > 2][0] = 100 # modifies a temporary copy
print(a) # [0 1 2 3 4 5]
a[a > 2] = 100 # a single assignment on a itself
print(a) # [ 0 1 2 100 100 100]Put the mask and the assignment in one expression. np.shares_memory(a, b) tells you whether two arrays overlap in memory.
Beware silent integer overflow
Fixed-width integers wrap around on overflow. NumPy does not raise an error for array arithmetic.
import numpy as np
p = np.array([200], dtype=np.uint8)
q = np.array([100], dtype=np.uint8)
print(p + q) # [44], because 300 wraps modulo 256
print(p.astype(np.int64) + q) # [300]Choose a dtype wide enough for your results. Cast with astype before arithmetic if the inputs are narrow. Narrow dtypes such as uint8 save memory, so use them deliberately and not by accident.
Mind memory layout
A transpose is a view with swapped strides, so it is free to create. Its data is no longer contiguous, though, and some operations run slower on it because they jump through memory. If you will reuse a transposed array many times, make one contiguous copy.
import numpy as np
a = np.arange(6).reshape(2, 3)
t = a.T
print(t.flags['C_CONTIGUOUS']) # False
c = np.ascontiguousarray(t)
print(c.flags['C_CONTIGUOUS']) # TrueQuick checklist
- Replace element loops with ufuncs, reductions, or broadcasting.
- Preallocate outputs and fill them.
- Do mask assignment in one step.
- Check dtypes before arithmetic that could overflow.
- Copy to contiguous memory only when profiling shows a gain.
Exercise
After running a = np.arange(6) and then b = a[[0, 1]] and b[0] = 50, what is a? Would the answer change if you used b = a[0:2] instead?
Show answer
In the first case a is still [0 1 2 3 4 5], because integer-list indexing returns a copy. With b = a[0:2] the slice is a view, so b[0] = 50 changes a to [50 1 2 3 4 5].