← Back to NumPy Course | Chapter 12: Advanced Topics | Lesson 6 of 7

Performance tips

A few habits, like vectorizing and choosing the right dtype, make NumPy code dramatically faster.

In this page:

  1. Performance tips

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

python
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
  1. Growing arrays inside loops
  2. Using float64 when float32 is enough
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.