Skip to main content
Albero Academy

Performance & Memory

Understand why NumPy is fast — contiguous memory, views and in-place ops.

Applied NumPy9 min

Knowing why NumPy is fast lets you keep it fast. The essentials: arrays are one contiguous memory block, many operations return cheap views, and staying vectorised avoids the Python-loop tax.

In-place operations

a += 1 reuses the existing buffer; a = a + 1 allocates a whole new array. For large arrays this matters:

avoid needless allocation
a *= 2 # in place — no new array
np.sqrt(a, out=a) # write the result back into a

Vectorise, don't loop

the difference
# Slow: Python loop
total = 0
for x in a:
total += x * x
# Fast: vectorised
total = (a * a).sum() # or a @ a

Key takeaways

  1. 01An ndarray is a contiguous buffer, so slices/reshape can be cheap views.
  2. 02In-place ops (a += 1, out=) reuse the buffer instead of allocating a new array.
  3. 03Replace element-wise Python loops with vectorised expressions for 10–100× speedups.
  4. 04Views share memory (fast); copies allocate — know which you have.

Finished this chapter?

Mark it complete to track your progress through NumPy.