Skip to main content
Albero Academy

Performance, Views & Memory

Understand why NumPy is fast — contiguous memory, views vs copies, in-place operations, and how to avoid needless allocations.

Chapter 14NumPy15 min readBeginner friendly
  • #NumPy
  • #Performance
  • #Memory

Knowing why NumPy is fast lets you keep it fast. The essentials: arrays are one contiguous block of memory, many operations return cheap views rather than copies, and staying vectorised avoids the Python-loop tax. A little awareness here turns slow code quick.

How arrays sit in memory

An ndarray is a flat contiguous buffer plus strides that describe how to step through it. That layout is why a reshape or transpose can be free — only the strides change, not the data:

the anatomy
a = np.arange(12).reshape(3, 4)
a.strides # bytes to step per dimension
a.flags['C_CONTIGUOUS'] # row-major layout?
a.nbytes # total bytes used
a.T.flags['C_CONTIGUOUS'] # False — transpose is a view with swapped strides

Views vs copies revisited

Slices and reshapes usually return a view (shares memory, free); fancy indexing and .copy() return a new array. Knowing which you have prevents both bugs and wasted memory:

which is it?
a = np.arange(10)
s = a[2:6] # view — shares memory
s.base is a # True → confirms it's a view
f = a[[2, 3, 4]] # fancy index — a copy
f.base is None # True → independent
a.reshape(2, 5).base is a # True → reshape is (usually) a view

In-place operations

a += 1 modifies the existing buffer; a = a + 1 allocates a whole new array. For large arrays in tight loops, in-place ops and the out= parameter save real time and memory:

avoid needless allocation
a *= 2 # in place — no new array
np.multiply(a, 2, out=a) # explicit in-place via out=
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

Practice

Take a slice and a fancy-index of the same array; use .base to prove one is a view and the other a copy. Rewrite a Python loop that squares and sums an array as a single vectorised expression and compare. Convert an a = a + 1 to an in-place a += 1 and explain the memory difference.

Key takeaways

  1. 01An ndarray is a contiguous buffer plus strides — so reshape/transpose can be free (view only).
  2. 02Slices and reshapes usually return views (shared memory); fancy indexing and .copy() allocate.
  3. 03Check .base to tell a view from a copy — avoids both aliasing bugs and wasted memory.
  4. 04In-place ops (a += 1, out=) reuse the buffer instead of allocating a new array.
  5. 05Replace element-wise Python loops with vectorised expressions for 10–100× speedups.